GNU Linux-libre 6.8.7-gnu
[releases.git] / fs / smb / client / smb2pdu.c
1 // SPDX-License-Identifier: LGPL-2.1
2 /*
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  */
12
13  /* SMB2 PDU handling routines here - except for leftovers (eg session setup) */
14  /* Note that there are handle based routines which must be                   */
15  /* treated slightly differently for reconnection purposes since we never     */
16  /* want to reuse a stale file handle and only the caller knows the file info */
17
18 #include <linux/fs.h>
19 #include <linux/kernel.h>
20 #include <linux/vfs.h>
21 #include <linux/task_io_accounting_ops.h>
22 #include <linux/uaccess.h>
23 #include <linux/uuid.h>
24 #include <linux/pagemap.h>
25 #include <linux/xattr.h>
26 #include "cifsglob.h"
27 #include "cifsacl.h"
28 #include "cifsproto.h"
29 #include "smb2proto.h"
30 #include "cifs_unicode.h"
31 #include "cifs_debug.h"
32 #include "ntlmssp.h"
33 #include "smb2status.h"
34 #include "smb2glob.h"
35 #include "cifspdu.h"
36 #include "cifs_spnego.h"
37 #include "smbdirect.h"
38 #include "trace.h"
39 #ifdef CONFIG_CIFS_DFS_UPCALL
40 #include "dfs_cache.h"
41 #endif
42 #include "cached_dir.h"
43
44 /*
45  *  The following table defines the expected "StructureSize" of SMB2 requests
46  *  in order by SMB2 command.  This is similar to "wct" in SMB/CIFS requests.
47  *
48  *  Note that commands are defined in smb2pdu.h in le16 but the array below is
49  *  indexed by command in host byte order.
50  */
51 static const int smb2_req_struct_sizes[NUMBER_OF_SMB2_COMMANDS] = {
52         /* SMB2_NEGOTIATE */ 36,
53         /* SMB2_SESSION_SETUP */ 25,
54         /* SMB2_LOGOFF */ 4,
55         /* SMB2_TREE_CONNECT */ 9,
56         /* SMB2_TREE_DISCONNECT */ 4,
57         /* SMB2_CREATE */ 57,
58         /* SMB2_CLOSE */ 24,
59         /* SMB2_FLUSH */ 24,
60         /* SMB2_READ */ 49,
61         /* SMB2_WRITE */ 49,
62         /* SMB2_LOCK */ 48,
63         /* SMB2_IOCTL */ 57,
64         /* SMB2_CANCEL */ 4,
65         /* SMB2_ECHO */ 4,
66         /* SMB2_QUERY_DIRECTORY */ 33,
67         /* SMB2_CHANGE_NOTIFY */ 32,
68         /* SMB2_QUERY_INFO */ 41,
69         /* SMB2_SET_INFO */ 33,
70         /* SMB2_OPLOCK_BREAK */ 24 /* BB this is 36 for LEASE_BREAK variant */
71 };
72
73 int smb3_encryption_required(const struct cifs_tcon *tcon)
74 {
75         if (!tcon || !tcon->ses)
76                 return 0;
77         if ((tcon->ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA) ||
78             (tcon->share_flags & SHI1005_FLAGS_ENCRYPT_DATA))
79                 return 1;
80         if (tcon->seal &&
81             (tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
82                 return 1;
83         return 0;
84 }
85
86 static void
87 smb2_hdr_assemble(struct smb2_hdr *shdr, __le16 smb2_cmd,
88                   const struct cifs_tcon *tcon,
89                   struct TCP_Server_Info *server)
90 {
91         struct smb3_hdr_req *smb3_hdr;
92
93         shdr->ProtocolId = SMB2_PROTO_NUMBER;
94         shdr->StructureSize = cpu_to_le16(64);
95         shdr->Command = smb2_cmd;
96
97         if (server) {
98                 /* After reconnect SMB3 must set ChannelSequence on subsequent reqs */
99                 if (server->dialect >= SMB30_PROT_ID) {
100                         smb3_hdr = (struct smb3_hdr_req *)shdr;
101                         /*
102                          * if primary channel is not set yet, use default
103                          * channel for chan sequence num
104                          */
105                         if (SERVER_IS_CHAN(server))
106                                 smb3_hdr->ChannelSequence =
107                                         cpu_to_le16(server->primary_server->channel_sequence_num);
108                         else
109                                 smb3_hdr->ChannelSequence =
110                                         cpu_to_le16(server->channel_sequence_num);
111                 }
112                 spin_lock(&server->req_lock);
113                 /* Request up to 10 credits but don't go over the limit. */
114                 if (server->credits >= server->max_credits)
115                         shdr->CreditRequest = cpu_to_le16(0);
116                 else
117                         shdr->CreditRequest = cpu_to_le16(
118                                 min_t(int, server->max_credits -
119                                                 server->credits, 10));
120                 spin_unlock(&server->req_lock);
121         } else {
122                 shdr->CreditRequest = cpu_to_le16(2);
123         }
124         shdr->Id.SyncId.ProcessId = cpu_to_le32((__u16)current->tgid);
125
126         if (!tcon)
127                 goto out;
128
129         /* GLOBAL_CAP_LARGE_MTU will only be set if dialect > SMB2.02 */
130         /* See sections 2.2.4 and 3.2.4.1.5 of MS-SMB2 */
131         if (server && (server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
132                 shdr->CreditCharge = cpu_to_le16(1);
133         /* else CreditCharge MBZ */
134
135         shdr->Id.SyncId.TreeId = cpu_to_le32(tcon->tid);
136         /* Uid is not converted */
137         if (tcon->ses)
138                 shdr->SessionId = cpu_to_le64(tcon->ses->Suid);
139
140         /*
141          * If we would set SMB2_FLAGS_DFS_OPERATIONS on open we also would have
142          * to pass the path on the Open SMB prefixed by \\server\share.
143          * Not sure when we would need to do the augmented path (if ever) and
144          * setting this flag breaks the SMB2 open operation since it is
145          * illegal to send an empty path name (without \\server\share prefix)
146          * when the DFS flag is set in the SMB open header. We could
147          * consider setting the flag on all operations other than open
148          * but it is safer to net set it for now.
149          */
150 /*      if (tcon->share_flags & SHI1005_FLAGS_DFS)
151                 shdr->Flags |= SMB2_FLAGS_DFS_OPERATIONS; */
152
153         if (server && server->sign && !smb3_encryption_required(tcon))
154                 shdr->Flags |= SMB2_FLAGS_SIGNED;
155 out:
156         return;
157 }
158
159 /* helper function for code reuse */
160 static int
161 cifs_chan_skip_or_disable(struct cifs_ses *ses,
162                           struct TCP_Server_Info *server,
163                           bool from_reconnect)
164 {
165         struct TCP_Server_Info *pserver;
166         unsigned int chan_index;
167
168         if (SERVER_IS_CHAN(server)) {
169                 cifs_dbg(VFS,
170                         "server %s does not support multichannel anymore. Skip secondary channel\n",
171                          ses->server->hostname);
172
173                 spin_lock(&ses->chan_lock);
174                 chan_index = cifs_ses_get_chan_index(ses, server);
175                 if (chan_index == CIFS_INVAL_CHAN_INDEX) {
176                         spin_unlock(&ses->chan_lock);
177                         goto skip_terminate;
178                 }
179
180                 ses->chans[chan_index].server = NULL;
181                 server->terminate = true;
182                 spin_unlock(&ses->chan_lock);
183
184                 /*
185                  * the above reference of server by channel
186                  * needs to be dropped without holding chan_lock
187                  * as cifs_put_tcp_session takes a higher lock
188                  * i.e. cifs_tcp_ses_lock
189                  */
190                 cifs_put_tcp_session(server, from_reconnect);
191
192                 cifs_signal_cifsd_for_reconnect(server, false);
193
194                 /* mark primary server as needing reconnect */
195                 pserver = server->primary_server;
196                 cifs_signal_cifsd_for_reconnect(pserver, false);
197 skip_terminate:
198                 return -EHOSTDOWN;
199         }
200
201         cifs_server_dbg(VFS,
202                 "server does not support multichannel anymore. Disable all other channels\n");
203         cifs_disable_secondary_channels(ses);
204
205
206         return 0;
207 }
208
209 static int
210 smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon,
211                struct TCP_Server_Info *server, bool from_reconnect)
212 {
213         int rc = 0;
214         struct nls_table *nls_codepage = NULL;
215         struct cifs_ses *ses;
216         int xid;
217
218         /*
219          * SMB2s NegProt, SessSetup, Logoff do not have tcon yet so
220          * check for tcp and smb session status done differently
221          * for those three - in the calling routine.
222          */
223         if (tcon == NULL)
224                 return 0;
225
226         /*
227          * Need to also skip SMB2_IOCTL because it is used for checking nested dfs links in
228          * cifs_tree_connect().
229          */
230         if (smb2_command == SMB2_TREE_CONNECT || smb2_command == SMB2_IOCTL)
231                 return 0;
232
233         spin_lock(&tcon->tc_lock);
234         if (tcon->status == TID_EXITING) {
235                 /*
236                  * only tree disconnect allowed when disconnecting ...
237                  */
238                 if (smb2_command != SMB2_TREE_DISCONNECT) {
239                         spin_unlock(&tcon->tc_lock);
240                         cifs_dbg(FYI, "can not send cmd %d while umounting\n",
241                                  smb2_command);
242                         return -ENODEV;
243                 }
244         }
245         spin_unlock(&tcon->tc_lock);
246
247         ses = tcon->ses;
248         if (!ses)
249                 return -EIO;
250         spin_lock(&ses->ses_lock);
251         if (ses->ses_status == SES_EXITING) {
252                 spin_unlock(&ses->ses_lock);
253                 return -EIO;
254         }
255         spin_unlock(&ses->ses_lock);
256         if (!ses->server || !server)
257                 return -EIO;
258
259         spin_lock(&server->srv_lock);
260         if (server->tcpStatus == CifsNeedReconnect) {
261                 /*
262                  * Return to caller for TREE_DISCONNECT and LOGOFF and CLOSE
263                  * here since they are implicitly done when session drops.
264                  */
265                 switch (smb2_command) {
266                 /*
267                  * BB Should we keep oplock break and add flush to exceptions?
268                  */
269                 case SMB2_TREE_DISCONNECT:
270                 case SMB2_CANCEL:
271                 case SMB2_CLOSE:
272                 case SMB2_OPLOCK_BREAK:
273                         spin_unlock(&server->srv_lock);
274                         return -EAGAIN;
275                 }
276         }
277
278         /* if server is marked for termination, cifsd will cleanup */
279         if (server->terminate) {
280                 spin_unlock(&server->srv_lock);
281                 return -EHOSTDOWN;
282         }
283         spin_unlock(&server->srv_lock);
284
285 again:
286         rc = cifs_wait_for_server_reconnect(server, tcon->retry);
287         if (rc)
288                 return rc;
289
290         spin_lock(&ses->chan_lock);
291         if (!cifs_chan_needs_reconnect(ses, server) && !tcon->need_reconnect) {
292                 spin_unlock(&ses->chan_lock);
293                 return 0;
294         }
295         spin_unlock(&ses->chan_lock);
296         cifs_dbg(FYI, "sess reconnect mask: 0x%lx, tcon reconnect: %d",
297                  tcon->ses->chans_need_reconnect,
298                  tcon->need_reconnect);
299
300         mutex_lock(&ses->session_mutex);
301         /*
302          * if this is called by delayed work, and the channel has been disabled
303          * in parallel, the delayed work can continue to execute in parallel
304          * there's a chance that this channel may not exist anymore
305          */
306         spin_lock(&server->srv_lock);
307         if (server->tcpStatus == CifsExiting) {
308                 spin_unlock(&server->srv_lock);
309                 mutex_unlock(&ses->session_mutex);
310                 rc = -EHOSTDOWN;
311                 goto out;
312         }
313
314         /*
315          * Recheck after acquire mutex. If another thread is negotiating
316          * and the server never sends an answer the socket will be closed
317          * and tcpStatus set to reconnect.
318          */
319         if (server->tcpStatus == CifsNeedReconnect) {
320                 spin_unlock(&server->srv_lock);
321                 mutex_unlock(&ses->session_mutex);
322
323                 if (tcon->retry)
324                         goto again;
325
326                 rc = -EHOSTDOWN;
327                 goto out;
328         }
329         spin_unlock(&server->srv_lock);
330
331         nls_codepage = ses->local_nls;
332
333         /*
334          * need to prevent multiple threads trying to simultaneously
335          * reconnect the same SMB session
336          */
337         spin_lock(&ses->ses_lock);
338         spin_lock(&ses->chan_lock);
339         if (!cifs_chan_needs_reconnect(ses, server) &&
340             ses->ses_status == SES_GOOD) {
341                 spin_unlock(&ses->chan_lock);
342                 spin_unlock(&ses->ses_lock);
343                 /* this means that we only need to tree connect */
344                 if (tcon->need_reconnect)
345                         goto skip_sess_setup;
346
347                 mutex_unlock(&ses->session_mutex);
348                 goto out;
349         }
350         spin_unlock(&ses->chan_lock);
351         spin_unlock(&ses->ses_lock);
352
353         rc = cifs_negotiate_protocol(0, ses, server);
354         if (!rc) {
355                 /*
356                  * if server stopped supporting multichannel
357                  * and the first channel reconnected, disable all the others.
358                  */
359                 if (ses->chan_count > 1 &&
360                     !(server->capabilities & SMB2_GLOBAL_CAP_MULTI_CHANNEL)) {
361                         rc = cifs_chan_skip_or_disable(ses, server,
362                                                        from_reconnect);
363                         if (rc) {
364                                 mutex_unlock(&ses->session_mutex);
365                                 goto out;
366                         }
367                 }
368
369                 rc = cifs_setup_session(0, ses, server, nls_codepage);
370                 if ((rc == -EACCES) && !tcon->retry) {
371                         mutex_unlock(&ses->session_mutex);
372                         rc = -EHOSTDOWN;
373                         goto failed;
374                 } else if (rc) {
375                         mutex_unlock(&ses->session_mutex);
376                         goto out;
377                 }
378         } else {
379                 mutex_unlock(&ses->session_mutex);
380                 goto out;
381         }
382
383 skip_sess_setup:
384         if (!tcon->need_reconnect) {
385                 mutex_unlock(&ses->session_mutex);
386                 goto out;
387         }
388         cifs_mark_open_files_invalid(tcon);
389         if (tcon->use_persistent)
390                 tcon->need_reopen_files = true;
391
392         rc = cifs_tree_connect(0, tcon, nls_codepage);
393
394         cifs_dbg(FYI, "reconnect tcon rc = %d\n", rc);
395         if (rc) {
396                 /* If sess reconnected but tcon didn't, something strange ... */
397                 mutex_unlock(&ses->session_mutex);
398                 cifs_dbg(VFS, "reconnect tcon failed rc = %d\n", rc);
399                 goto out;
400         }
401
402         spin_lock(&ses->ses_lock);
403         if (ses->flags & CIFS_SES_FLAG_SCALE_CHANNELS) {
404                 spin_unlock(&ses->ses_lock);
405                 mutex_unlock(&ses->session_mutex);
406                 goto skip_add_channels;
407         }
408         ses->flags |= CIFS_SES_FLAG_SCALE_CHANNELS;
409         spin_unlock(&ses->ses_lock);
410
411         if (!rc &&
412             (server->capabilities & SMB2_GLOBAL_CAP_MULTI_CHANNEL) &&
413             server->ops->query_server_interfaces) {
414                 mutex_unlock(&ses->session_mutex);
415
416                 /*
417                  * query server network interfaces, in case they change
418                  */
419                 xid = get_xid();
420                 rc = server->ops->query_server_interfaces(xid, tcon, false);
421                 free_xid(xid);
422
423                 if (rc == -EOPNOTSUPP && ses->chan_count > 1) {
424                         /*
425                          * some servers like Azure SMB server do not advertise
426                          * that multichannel has been disabled with server
427                          * capabilities, rather return STATUS_NOT_IMPLEMENTED.
428                          * treat this as server not supporting multichannel
429                          */
430
431                         rc = cifs_chan_skip_or_disable(ses, server,
432                                                        from_reconnect);
433                         goto skip_add_channels;
434                 } else if (rc)
435                         cifs_dbg(FYI, "%s: failed to query server interfaces: %d\n",
436                                  __func__, rc);
437
438                 if (ses->chan_max > ses->chan_count &&
439                     ses->iface_count &&
440                     !SERVER_IS_CHAN(server)) {
441                         if (ses->chan_count == 1) {
442                                 cifs_server_dbg(VFS, "supports multichannel now\n");
443                                 queue_delayed_work(cifsiod_wq, &tcon->query_interfaces,
444                                                  (SMB_INTERFACE_POLL_INTERVAL * HZ));
445                         }
446
447                         cifs_try_adding_channels(ses);
448                 }
449         } else {
450                 mutex_unlock(&ses->session_mutex);
451         }
452
453 skip_add_channels:
454         spin_lock(&ses->ses_lock);
455         ses->flags &= ~CIFS_SES_FLAG_SCALE_CHANNELS;
456         spin_unlock(&ses->ses_lock);
457
458         if (smb2_command != SMB2_INTERNAL_CMD)
459                 mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
460
461         atomic_inc(&tconInfoReconnectCount);
462 out:
463         /*
464          * Check if handle based operation so we know whether we can continue
465          * or not without returning to caller to reset file handle.
466          */
467         /*
468          * BB Is flush done by server on drop of tcp session? Should we special
469          * case it and skip above?
470          */
471         switch (smb2_command) {
472         case SMB2_FLUSH:
473         case SMB2_READ:
474         case SMB2_WRITE:
475         case SMB2_LOCK:
476         case SMB2_QUERY_DIRECTORY:
477         case SMB2_CHANGE_NOTIFY:
478         case SMB2_QUERY_INFO:
479         case SMB2_SET_INFO:
480                 rc = -EAGAIN;
481         }
482 failed:
483         return rc;
484 }
485
486 static void
487 fill_small_buf(__le16 smb2_command, struct cifs_tcon *tcon,
488                struct TCP_Server_Info *server,
489                void *buf,
490                unsigned int *total_len)
491 {
492         struct smb2_pdu *spdu = buf;
493         /* lookup word count ie StructureSize from table */
494         __u16 parmsize = smb2_req_struct_sizes[le16_to_cpu(smb2_command)];
495
496         /*
497          * smaller than SMALL_BUFFER_SIZE but bigger than fixed area of
498          * largest operations (Create)
499          */
500         memset(buf, 0, 256);
501
502         smb2_hdr_assemble(&spdu->hdr, smb2_command, tcon, server);
503         spdu->StructureSize2 = cpu_to_le16(parmsize);
504
505         *total_len = parmsize + sizeof(struct smb2_hdr);
506 }
507
508 /*
509  * Allocate and return pointer to an SMB request hdr, and set basic
510  * SMB information in the SMB header. If the return code is zero, this
511  * function must have filled in request_buf pointer.
512  */
513 static int __smb2_plain_req_init(__le16 smb2_command, struct cifs_tcon *tcon,
514                                  struct TCP_Server_Info *server,
515                                  void **request_buf, unsigned int *total_len)
516 {
517         /* BB eventually switch this to SMB2 specific small buf size */
518         switch (smb2_command) {
519         case SMB2_SET_INFO:
520         case SMB2_QUERY_INFO:
521                 *request_buf = cifs_buf_get();
522                 break;
523         default:
524                 *request_buf = cifs_small_buf_get();
525                 break;
526         }
527         if (*request_buf == NULL) {
528                 /* BB should we add a retry in here if not a writepage? */
529                 return -ENOMEM;
530         }
531
532         fill_small_buf(smb2_command, tcon, server,
533                        (struct smb2_hdr *)(*request_buf),
534                        total_len);
535
536         if (tcon != NULL) {
537                 uint16_t com_code = le16_to_cpu(smb2_command);
538                 cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_sent[com_code]);
539                 cifs_stats_inc(&tcon->num_smbs_sent);
540         }
541
542         return 0;
543 }
544
545 static int smb2_plain_req_init(__le16 smb2_command, struct cifs_tcon *tcon,
546                                struct TCP_Server_Info *server,
547                                void **request_buf, unsigned int *total_len)
548 {
549         int rc;
550
551         rc = smb2_reconnect(smb2_command, tcon, server, false);
552         if (rc)
553                 return rc;
554
555         return __smb2_plain_req_init(smb2_command, tcon, server, request_buf,
556                                      total_len);
557 }
558
559 static int smb2_ioctl_req_init(u32 opcode, struct cifs_tcon *tcon,
560                                struct TCP_Server_Info *server,
561                                void **request_buf, unsigned int *total_len)
562 {
563         /* Skip reconnect only for FSCTL_VALIDATE_NEGOTIATE_INFO IOCTLs */
564         if (opcode == FSCTL_VALIDATE_NEGOTIATE_INFO) {
565                 return __smb2_plain_req_init(SMB2_IOCTL, tcon, server,
566                                              request_buf, total_len);
567         }
568         return smb2_plain_req_init(SMB2_IOCTL, tcon, server,
569                                    request_buf, total_len);
570 }
571
572 /* For explanation of negotiate contexts see MS-SMB2 section 2.2.3.1 */
573
574 static void
575 build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt)
576 {
577         pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
578         pneg_ctxt->DataLength = cpu_to_le16(38);
579         pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
580         pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
581         get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
582         pneg_ctxt->HashAlgorithms = SMB2_PREAUTH_INTEGRITY_SHA512;
583 }
584
585 static void
586 build_compression_ctxt(struct smb2_compression_capabilities_context *pneg_ctxt)
587 {
588         pneg_ctxt->ContextType = SMB2_COMPRESSION_CAPABILITIES;
589         pneg_ctxt->DataLength =
590                 cpu_to_le16(sizeof(struct smb2_compression_capabilities_context)
591                           - sizeof(struct smb2_neg_context));
592         pneg_ctxt->CompressionAlgorithmCount = cpu_to_le16(3);
593         pneg_ctxt->CompressionAlgorithms[0] = SMB3_COMPRESS_LZ77;
594         pneg_ctxt->CompressionAlgorithms[1] = SMB3_COMPRESS_LZ77_HUFF;
595         pneg_ctxt->CompressionAlgorithms[2] = SMB3_COMPRESS_LZNT1;
596 }
597
598 static unsigned int
599 build_signing_ctxt(struct smb2_signing_capabilities *pneg_ctxt)
600 {
601         unsigned int ctxt_len = sizeof(struct smb2_signing_capabilities);
602         unsigned short num_algs = 1; /* number of signing algorithms sent */
603
604         pneg_ctxt->ContextType = SMB2_SIGNING_CAPABILITIES;
605         /*
606          * Context Data length must be rounded to multiple of 8 for some servers
607          */
608         pneg_ctxt->DataLength = cpu_to_le16(ALIGN(sizeof(struct smb2_signing_capabilities) -
609                                             sizeof(struct smb2_neg_context) +
610                                             (num_algs * sizeof(u16)), 8));
611         pneg_ctxt->SigningAlgorithmCount = cpu_to_le16(num_algs);
612         pneg_ctxt->SigningAlgorithms[0] = cpu_to_le16(SIGNING_ALG_AES_CMAC);
613
614         ctxt_len += sizeof(__le16) * num_algs;
615         ctxt_len = ALIGN(ctxt_len, 8);
616         return ctxt_len;
617         /* TBD add SIGNING_ALG_AES_GMAC and/or SIGNING_ALG_HMAC_SHA256 */
618 }
619
620 static void
621 build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt)
622 {
623         pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
624         if (require_gcm_256) {
625                 pneg_ctxt->DataLength = cpu_to_le16(4); /* Cipher Count + 1 cipher */
626                 pneg_ctxt->CipherCount = cpu_to_le16(1);
627                 pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES256_GCM;
628         } else if (enable_gcm_256) {
629                 pneg_ctxt->DataLength = cpu_to_le16(8); /* Cipher Count + 3 ciphers */
630                 pneg_ctxt->CipherCount = cpu_to_le16(3);
631                 pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES128_GCM;
632                 pneg_ctxt->Ciphers[1] = SMB2_ENCRYPTION_AES256_GCM;
633                 pneg_ctxt->Ciphers[2] = SMB2_ENCRYPTION_AES128_CCM;
634         } else {
635                 pneg_ctxt->DataLength = cpu_to_le16(6); /* Cipher Count + 2 ciphers */
636                 pneg_ctxt->CipherCount = cpu_to_le16(2);
637                 pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES128_GCM;
638                 pneg_ctxt->Ciphers[1] = SMB2_ENCRYPTION_AES128_CCM;
639         }
640 }
641
642 static unsigned int
643 build_netname_ctxt(struct smb2_netname_neg_context *pneg_ctxt, char *hostname)
644 {
645         struct nls_table *cp = load_nls_default();
646
647         pneg_ctxt->ContextType = SMB2_NETNAME_NEGOTIATE_CONTEXT_ID;
648
649         /* copy up to max of first 100 bytes of server name to NetName field */
650         pneg_ctxt->DataLength = cpu_to_le16(2 * cifs_strtoUTF16(pneg_ctxt->NetName, hostname, 100, cp));
651         /* context size is DataLength + minimal smb2_neg_context */
652         return ALIGN(le16_to_cpu(pneg_ctxt->DataLength) + sizeof(struct smb2_neg_context), 8);
653 }
654
655 static void
656 build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
657 {
658         pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
659         pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
660         /* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
661         pneg_ctxt->Name[0] = 0x93;
662         pneg_ctxt->Name[1] = 0xAD;
663         pneg_ctxt->Name[2] = 0x25;
664         pneg_ctxt->Name[3] = 0x50;
665         pneg_ctxt->Name[4] = 0x9C;
666         pneg_ctxt->Name[5] = 0xB4;
667         pneg_ctxt->Name[6] = 0x11;
668         pneg_ctxt->Name[7] = 0xE7;
669         pneg_ctxt->Name[8] = 0xB4;
670         pneg_ctxt->Name[9] = 0x23;
671         pneg_ctxt->Name[10] = 0x83;
672         pneg_ctxt->Name[11] = 0xDE;
673         pneg_ctxt->Name[12] = 0x96;
674         pneg_ctxt->Name[13] = 0x8B;
675         pneg_ctxt->Name[14] = 0xCD;
676         pneg_ctxt->Name[15] = 0x7C;
677 }
678
679 static void
680 assemble_neg_contexts(struct smb2_negotiate_req *req,
681                       struct TCP_Server_Info *server, unsigned int *total_len)
682 {
683         unsigned int ctxt_len, neg_context_count;
684         struct TCP_Server_Info *pserver;
685         char *pneg_ctxt;
686         char *hostname;
687
688         if (*total_len > 200) {
689                 /* In case length corrupted don't want to overrun smb buffer */
690                 cifs_server_dbg(VFS, "Bad frame length assembling neg contexts\n");
691                 return;
692         }
693
694         /*
695          * round up total_len of fixed part of SMB3 negotiate request to 8
696          * byte boundary before adding negotiate contexts
697          */
698         *total_len = ALIGN(*total_len, 8);
699
700         pneg_ctxt = (*total_len) + (char *)req;
701         req->NegotiateContextOffset = cpu_to_le32(*total_len);
702
703         build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt);
704         ctxt_len = ALIGN(sizeof(struct smb2_preauth_neg_context), 8);
705         *total_len += ctxt_len;
706         pneg_ctxt += ctxt_len;
707
708         build_encrypt_ctxt((struct smb2_encryption_neg_context *)pneg_ctxt);
709         ctxt_len = ALIGN(sizeof(struct smb2_encryption_neg_context), 8);
710         *total_len += ctxt_len;
711         pneg_ctxt += ctxt_len;
712
713         /*
714          * secondary channels don't have the hostname field populated
715          * use the hostname field in the primary channel instead
716          */
717         pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
718         cifs_server_lock(pserver);
719         hostname = pserver->hostname;
720         if (hostname && (hostname[0] != 0)) {
721                 ctxt_len = build_netname_ctxt((struct smb2_netname_neg_context *)pneg_ctxt,
722                                               hostname);
723                 *total_len += ctxt_len;
724                 pneg_ctxt += ctxt_len;
725                 neg_context_count = 3;
726         } else
727                 neg_context_count = 2;
728         cifs_server_unlock(pserver);
729
730         build_posix_ctxt((struct smb2_posix_neg_context *)pneg_ctxt);
731         *total_len += sizeof(struct smb2_posix_neg_context);
732         pneg_ctxt += sizeof(struct smb2_posix_neg_context);
733         neg_context_count++;
734
735         if (server->compress_algorithm) {
736                 build_compression_ctxt((struct smb2_compression_capabilities_context *)
737                                 pneg_ctxt);
738                 ctxt_len = ALIGN(sizeof(struct smb2_compression_capabilities_context), 8);
739                 *total_len += ctxt_len;
740                 pneg_ctxt += ctxt_len;
741                 neg_context_count++;
742         }
743
744         if (enable_negotiate_signing) {
745                 ctxt_len = build_signing_ctxt((struct smb2_signing_capabilities *)
746                                 pneg_ctxt);
747                 *total_len += ctxt_len;
748                 pneg_ctxt += ctxt_len;
749                 neg_context_count++;
750         }
751
752         /* check for and add transport_capabilities and signing capabilities */
753         req->NegotiateContextCount = cpu_to_le16(neg_context_count);
754
755 }
756
757 /* If invalid preauth context warn but use what we requested, SHA-512 */
758 static void decode_preauth_context(struct smb2_preauth_neg_context *ctxt)
759 {
760         unsigned int len = le16_to_cpu(ctxt->DataLength);
761
762         /*
763          * Caller checked that DataLength remains within SMB boundary. We still
764          * need to confirm that one HashAlgorithms member is accounted for.
765          */
766         if (len < MIN_PREAUTH_CTXT_DATA_LEN) {
767                 pr_warn_once("server sent bad preauth context\n");
768                 return;
769         } else if (len < MIN_PREAUTH_CTXT_DATA_LEN + le16_to_cpu(ctxt->SaltLength)) {
770                 pr_warn_once("server sent invalid SaltLength\n");
771                 return;
772         }
773         if (le16_to_cpu(ctxt->HashAlgorithmCount) != 1)
774                 pr_warn_once("Invalid SMB3 hash algorithm count\n");
775         if (ctxt->HashAlgorithms != SMB2_PREAUTH_INTEGRITY_SHA512)
776                 pr_warn_once("unknown SMB3 hash algorithm\n");
777 }
778
779 static void decode_compress_ctx(struct TCP_Server_Info *server,
780                          struct smb2_compression_capabilities_context *ctxt)
781 {
782         unsigned int len = le16_to_cpu(ctxt->DataLength);
783
784         /*
785          * Caller checked that DataLength remains within SMB boundary. We still
786          * need to confirm that one CompressionAlgorithms member is accounted
787          * for.
788          */
789         if (len < 10) {
790                 pr_warn_once("server sent bad compression cntxt\n");
791                 return;
792         }
793         if (le16_to_cpu(ctxt->CompressionAlgorithmCount) != 1) {
794                 pr_warn_once("Invalid SMB3 compress algorithm count\n");
795                 return;
796         }
797         if (le16_to_cpu(ctxt->CompressionAlgorithms[0]) > 3) {
798                 pr_warn_once("unknown compression algorithm\n");
799                 return;
800         }
801         server->compress_algorithm = ctxt->CompressionAlgorithms[0];
802 }
803
804 static int decode_encrypt_ctx(struct TCP_Server_Info *server,
805                               struct smb2_encryption_neg_context *ctxt)
806 {
807         unsigned int len = le16_to_cpu(ctxt->DataLength);
808
809         cifs_dbg(FYI, "decode SMB3.11 encryption neg context of len %d\n", len);
810         /*
811          * Caller checked that DataLength remains within SMB boundary. We still
812          * need to confirm that one Cipher flexible array member is accounted
813          * for.
814          */
815         if (len < MIN_ENCRYPT_CTXT_DATA_LEN) {
816                 pr_warn_once("server sent bad crypto ctxt len\n");
817                 return -EINVAL;
818         }
819
820         if (le16_to_cpu(ctxt->CipherCount) != 1) {
821                 pr_warn_once("Invalid SMB3.11 cipher count\n");
822                 return -EINVAL;
823         }
824         cifs_dbg(FYI, "SMB311 cipher type:%d\n", le16_to_cpu(ctxt->Ciphers[0]));
825         if (require_gcm_256) {
826                 if (ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES256_GCM) {
827                         cifs_dbg(VFS, "Server does not support requested encryption type (AES256 GCM)\n");
828                         return -EOPNOTSUPP;
829                 }
830         } else if (ctxt->Ciphers[0] == 0) {
831                 /*
832                  * e.g. if server only supported AES256_CCM (very unlikely)
833                  * or server supported no encryption types or had all disabled.
834                  * Since GLOBAL_CAP_ENCRYPTION will be not set, in the case
835                  * in which mount requested encryption ("seal") checks later
836                  * on during tree connection will return proper rc, but if
837                  * seal not requested by client, since server is allowed to
838                  * return 0 to indicate no supported cipher, we can't fail here
839                  */
840                 server->cipher_type = 0;
841                 server->capabilities &= ~SMB2_GLOBAL_CAP_ENCRYPTION;
842                 pr_warn_once("Server does not support requested encryption types\n");
843                 return 0;
844         } else if ((ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES128_CCM) &&
845                    (ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES128_GCM) &&
846                    (ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES256_GCM)) {
847                 /* server returned a cipher we didn't ask for */
848                 pr_warn_once("Invalid SMB3.11 cipher returned\n");
849                 return -EINVAL;
850         }
851         server->cipher_type = ctxt->Ciphers[0];
852         server->capabilities |= SMB2_GLOBAL_CAP_ENCRYPTION;
853         return 0;
854 }
855
856 static void decode_signing_ctx(struct TCP_Server_Info *server,
857                                struct smb2_signing_capabilities *pctxt)
858 {
859         unsigned int len = le16_to_cpu(pctxt->DataLength);
860
861         /*
862          * Caller checked that DataLength remains within SMB boundary. We still
863          * need to confirm that one SigningAlgorithms flexible array member is
864          * accounted for.
865          */
866         if ((len < 4) || (len > 16)) {
867                 pr_warn_once("server sent bad signing negcontext\n");
868                 return;
869         }
870         if (le16_to_cpu(pctxt->SigningAlgorithmCount) != 1) {
871                 pr_warn_once("Invalid signing algorithm count\n");
872                 return;
873         }
874         if (le16_to_cpu(pctxt->SigningAlgorithms[0]) > 2) {
875                 pr_warn_once("unknown signing algorithm\n");
876                 return;
877         }
878
879         server->signing_negotiated = true;
880         server->signing_algorithm = le16_to_cpu(pctxt->SigningAlgorithms[0]);
881         cifs_dbg(FYI, "signing algorithm %d chosen\n",
882                      server->signing_algorithm);
883 }
884
885
886 static int smb311_decode_neg_context(struct smb2_negotiate_rsp *rsp,
887                                      struct TCP_Server_Info *server,
888                                      unsigned int len_of_smb)
889 {
890         struct smb2_neg_context *pctx;
891         unsigned int offset = le32_to_cpu(rsp->NegotiateContextOffset);
892         unsigned int ctxt_cnt = le16_to_cpu(rsp->NegotiateContextCount);
893         unsigned int len_of_ctxts, i;
894         int rc = 0;
895
896         cifs_dbg(FYI, "decoding %d negotiate contexts\n", ctxt_cnt);
897         if (len_of_smb <= offset) {
898                 cifs_server_dbg(VFS, "Invalid response: negotiate context offset\n");
899                 return -EINVAL;
900         }
901
902         len_of_ctxts = len_of_smb - offset;
903
904         for (i = 0; i < ctxt_cnt; i++) {
905                 int clen;
906                 /* check that offset is not beyond end of SMB */
907                 if (len_of_ctxts < sizeof(struct smb2_neg_context))
908                         break;
909
910                 pctx = (struct smb2_neg_context *)(offset + (char *)rsp);
911                 clen = sizeof(struct smb2_neg_context)
912                         + le16_to_cpu(pctx->DataLength);
913                 /*
914                  * 2.2.4 SMB2 NEGOTIATE Response
915                  * Subsequent negotiate contexts MUST appear at the first 8-byte
916                  * aligned offset following the previous negotiate context.
917                  */
918                 if (i + 1 != ctxt_cnt)
919                         clen = ALIGN(clen, 8);
920                 if (clen > len_of_ctxts)
921                         break;
922
923                 if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES)
924                         decode_preauth_context(
925                                 (struct smb2_preauth_neg_context *)pctx);
926                 else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES)
927                         rc = decode_encrypt_ctx(server,
928                                 (struct smb2_encryption_neg_context *)pctx);
929                 else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES)
930                         decode_compress_ctx(server,
931                                 (struct smb2_compression_capabilities_context *)pctx);
932                 else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE)
933                         server->posix_ext_supported = true;
934                 else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES)
935                         decode_signing_ctx(server,
936                                 (struct smb2_signing_capabilities *)pctx);
937                 else
938                         cifs_server_dbg(VFS, "unknown negcontext of type %d ignored\n",
939                                 le16_to_cpu(pctx->ContextType));
940                 if (rc)
941                         break;
942
943                 offset += clen;
944                 len_of_ctxts -= clen;
945         }
946         return rc;
947 }
948
949 static struct create_posix *
950 create_posix_buf(umode_t mode)
951 {
952         struct create_posix *buf;
953
954         buf = kzalloc(sizeof(struct create_posix),
955                         GFP_KERNEL);
956         if (!buf)
957                 return NULL;
958
959         buf->ccontext.DataOffset =
960                 cpu_to_le16(offsetof(struct create_posix, Mode));
961         buf->ccontext.DataLength = cpu_to_le32(4);
962         buf->ccontext.NameOffset =
963                 cpu_to_le16(offsetof(struct create_posix, Name));
964         buf->ccontext.NameLength = cpu_to_le16(16);
965
966         /* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
967         buf->Name[0] = 0x93;
968         buf->Name[1] = 0xAD;
969         buf->Name[2] = 0x25;
970         buf->Name[3] = 0x50;
971         buf->Name[4] = 0x9C;
972         buf->Name[5] = 0xB4;
973         buf->Name[6] = 0x11;
974         buf->Name[7] = 0xE7;
975         buf->Name[8] = 0xB4;
976         buf->Name[9] = 0x23;
977         buf->Name[10] = 0x83;
978         buf->Name[11] = 0xDE;
979         buf->Name[12] = 0x96;
980         buf->Name[13] = 0x8B;
981         buf->Name[14] = 0xCD;
982         buf->Name[15] = 0x7C;
983         buf->Mode = cpu_to_le32(mode);
984         cifs_dbg(FYI, "mode on posix create 0%o\n", mode);
985         return buf;
986 }
987
988 static int
989 add_posix_context(struct kvec *iov, unsigned int *num_iovec, umode_t mode)
990 {
991         unsigned int num = *num_iovec;
992
993         iov[num].iov_base = create_posix_buf(mode);
994         if (mode == ACL_NO_MODE)
995                 cifs_dbg(FYI, "%s: no mode\n", __func__);
996         if (iov[num].iov_base == NULL)
997                 return -ENOMEM;
998         iov[num].iov_len = sizeof(struct create_posix);
999         *num_iovec = num + 1;
1000         return 0;
1001 }
1002
1003
1004 /*
1005  *
1006  *      SMB2 Worker functions follow:
1007  *
1008  *      The general structure of the worker functions is:
1009  *      1) Call smb2_init (assembles SMB2 header)
1010  *      2) Initialize SMB2 command specific fields in fixed length area of SMB
1011  *      3) Call smb_sendrcv2 (sends request on socket and waits for response)
1012  *      4) Decode SMB2 command specific fields in the fixed length area
1013  *      5) Decode variable length data area (if any for this SMB2 command type)
1014  *      6) Call free smb buffer
1015  *      7) return
1016  *
1017  */
1018
1019 int
1020 SMB2_negotiate(const unsigned int xid,
1021                struct cifs_ses *ses,
1022                struct TCP_Server_Info *server)
1023 {
1024         struct smb_rqst rqst;
1025         struct smb2_negotiate_req *req;
1026         struct smb2_negotiate_rsp *rsp;
1027         struct kvec iov[1];
1028         struct kvec rsp_iov;
1029         int rc;
1030         int resp_buftype;
1031         int blob_offset, blob_length;
1032         char *security_blob;
1033         int flags = CIFS_NEG_OP;
1034         unsigned int total_len;
1035
1036         cifs_dbg(FYI, "Negotiate protocol\n");
1037
1038         if (!server) {
1039                 WARN(1, "%s: server is NULL!\n", __func__);
1040                 return -EIO;
1041         }
1042
1043         rc = smb2_plain_req_init(SMB2_NEGOTIATE, NULL, server,
1044                                  (void **) &req, &total_len);
1045         if (rc)
1046                 return rc;
1047
1048         req->hdr.SessionId = 0;
1049
1050         memset(server->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE);
1051         memset(ses->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE);
1052
1053         if (strcmp(server->vals->version_string,
1054                    SMB3ANY_VERSION_STRING) == 0) {
1055                 req->Dialects[0] = cpu_to_le16(SMB30_PROT_ID);
1056                 req->Dialects[1] = cpu_to_le16(SMB302_PROT_ID);
1057                 req->Dialects[2] = cpu_to_le16(SMB311_PROT_ID);
1058                 req->DialectCount = cpu_to_le16(3);
1059                 total_len += 6;
1060         } else if (strcmp(server->vals->version_string,
1061                    SMBDEFAULT_VERSION_STRING) == 0) {
1062                 req->Dialects[0] = cpu_to_le16(SMB21_PROT_ID);
1063                 req->Dialects[1] = cpu_to_le16(SMB30_PROT_ID);
1064                 req->Dialects[2] = cpu_to_le16(SMB302_PROT_ID);
1065                 req->Dialects[3] = cpu_to_le16(SMB311_PROT_ID);
1066                 req->DialectCount = cpu_to_le16(4);
1067                 total_len += 8;
1068         } else {
1069                 /* otherwise send specific dialect */
1070                 req->Dialects[0] = cpu_to_le16(server->vals->protocol_id);
1071                 req->DialectCount = cpu_to_le16(1);
1072                 total_len += 2;
1073         }
1074
1075         /* only one of SMB2 signing flags may be set in SMB2 request */
1076         if (ses->sign)
1077                 req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
1078         else if (global_secflags & CIFSSEC_MAY_SIGN)
1079                 req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
1080         else
1081                 req->SecurityMode = 0;
1082
1083         req->Capabilities = cpu_to_le32(server->vals->req_capabilities);
1084         if (ses->chan_max > 1)
1085                 req->Capabilities |= cpu_to_le32(SMB2_GLOBAL_CAP_MULTI_CHANNEL);
1086
1087         /* ClientGUID must be zero for SMB2.02 dialect */
1088         if (server->vals->protocol_id == SMB20_PROT_ID)
1089                 memset(req->ClientGUID, 0, SMB2_CLIENT_GUID_SIZE);
1090         else {
1091                 memcpy(req->ClientGUID, server->client_guid,
1092                         SMB2_CLIENT_GUID_SIZE);
1093                 if ((server->vals->protocol_id == SMB311_PROT_ID) ||
1094                     (strcmp(server->vals->version_string,
1095                      SMB3ANY_VERSION_STRING) == 0) ||
1096                     (strcmp(server->vals->version_string,
1097                      SMBDEFAULT_VERSION_STRING) == 0))
1098                         assemble_neg_contexts(req, server, &total_len);
1099         }
1100         iov[0].iov_base = (char *)req;
1101         iov[0].iov_len = total_len;
1102
1103         memset(&rqst, 0, sizeof(struct smb_rqst));
1104         rqst.rq_iov = iov;
1105         rqst.rq_nvec = 1;
1106
1107         rc = cifs_send_recv(xid, ses, server,
1108                             &rqst, &resp_buftype, flags, &rsp_iov);
1109         cifs_small_buf_release(req);
1110         rsp = (struct smb2_negotiate_rsp *)rsp_iov.iov_base;
1111         /*
1112          * No tcon so can't do
1113          * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
1114          */
1115         if (rc == -EOPNOTSUPP) {
1116                 cifs_server_dbg(VFS, "Dialect not supported by server. Consider  specifying vers=1.0 or vers=2.0 on mount for accessing older servers\n");
1117                 goto neg_exit;
1118         } else if (rc != 0)
1119                 goto neg_exit;
1120
1121         rc = -EIO;
1122         if (strcmp(server->vals->version_string,
1123                    SMB3ANY_VERSION_STRING) == 0) {
1124                 if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) {
1125                         cifs_server_dbg(VFS,
1126                                 "SMB2 dialect returned but not requested\n");
1127                         goto neg_exit;
1128                 } else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) {
1129                         cifs_server_dbg(VFS,
1130                                 "SMB2.1 dialect returned but not requested\n");
1131                         goto neg_exit;
1132                 } else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) {
1133                         /* ops set to 3.0 by default for default so update */
1134                         server->ops = &smb311_operations;
1135                         server->vals = &smb311_values;
1136                 }
1137         } else if (strcmp(server->vals->version_string,
1138                    SMBDEFAULT_VERSION_STRING) == 0) {
1139                 if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) {
1140                         cifs_server_dbg(VFS,
1141                                 "SMB2 dialect returned but not requested\n");
1142                         goto neg_exit;
1143                 } else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) {
1144                         /* ops set to 3.0 by default for default so update */
1145                         server->ops = &smb21_operations;
1146                         server->vals = &smb21_values;
1147                 } else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) {
1148                         server->ops = &smb311_operations;
1149                         server->vals = &smb311_values;
1150                 }
1151         } else if (le16_to_cpu(rsp->DialectRevision) !=
1152                                 server->vals->protocol_id) {
1153                 /* if requested single dialect ensure returned dialect matched */
1154                 cifs_server_dbg(VFS, "Invalid 0x%x dialect returned: not requested\n",
1155                                 le16_to_cpu(rsp->DialectRevision));
1156                 goto neg_exit;
1157         }
1158
1159         cifs_dbg(FYI, "mode 0x%x\n", rsp->SecurityMode);
1160
1161         if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID))
1162                 cifs_dbg(FYI, "negotiated smb2.0 dialect\n");
1163         else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID))
1164                 cifs_dbg(FYI, "negotiated smb2.1 dialect\n");
1165         else if (rsp->DialectRevision == cpu_to_le16(SMB30_PROT_ID))
1166                 cifs_dbg(FYI, "negotiated smb3.0 dialect\n");
1167         else if (rsp->DialectRevision == cpu_to_le16(SMB302_PROT_ID))
1168                 cifs_dbg(FYI, "negotiated smb3.02 dialect\n");
1169         else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID))
1170                 cifs_dbg(FYI, "negotiated smb3.1.1 dialect\n");
1171         else {
1172                 cifs_server_dbg(VFS, "Invalid dialect returned by server 0x%x\n",
1173                                 le16_to_cpu(rsp->DialectRevision));
1174                 goto neg_exit;
1175         }
1176
1177         rc = 0;
1178         server->dialect = le16_to_cpu(rsp->DialectRevision);
1179
1180         /*
1181          * Keep a copy of the hash after negprot. This hash will be
1182          * the starting hash value for all sessions made from this
1183          * server.
1184          */
1185         memcpy(server->preauth_sha_hash, ses->preauth_sha_hash,
1186                SMB2_PREAUTH_HASH_SIZE);
1187
1188         /* SMB2 only has an extended negflavor */
1189         server->negflavor = CIFS_NEGFLAVOR_EXTENDED;
1190         /* set it to the maximum buffer size value we can send with 1 credit */
1191         server->maxBuf = min_t(unsigned int, le32_to_cpu(rsp->MaxTransactSize),
1192                                SMB2_MAX_BUFFER_SIZE);
1193         server->max_read = le32_to_cpu(rsp->MaxReadSize);
1194         server->max_write = le32_to_cpu(rsp->MaxWriteSize);
1195         server->sec_mode = le16_to_cpu(rsp->SecurityMode);
1196         if ((server->sec_mode & SMB2_SEC_MODE_FLAGS_ALL) != server->sec_mode)
1197                 cifs_dbg(FYI, "Server returned unexpected security mode 0x%x\n",
1198                                 server->sec_mode);
1199         server->capabilities = le32_to_cpu(rsp->Capabilities);
1200         /* Internal types */
1201         server->capabilities |= SMB2_NT_FIND | SMB2_LARGE_FILES;
1202
1203         /*
1204          * SMB3.0 supports only 1 cipher and doesn't have a encryption neg context
1205          * Set the cipher type manually.
1206          */
1207         if (server->dialect == SMB30_PROT_ID && (server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
1208                 server->cipher_type = SMB2_ENCRYPTION_AES128_CCM;
1209
1210         security_blob = smb2_get_data_area_len(&blob_offset, &blob_length,
1211                                                (struct smb2_hdr *)rsp);
1212         /*
1213          * See MS-SMB2 section 2.2.4: if no blob, client picks default which
1214          * for us will be
1215          *      ses->sectype = RawNTLMSSP;
1216          * but for time being this is our only auth choice so doesn't matter.
1217          * We just found a server which sets blob length to zero expecting raw.
1218          */
1219         if (blob_length == 0) {
1220                 cifs_dbg(FYI, "missing security blob on negprot\n");
1221                 server->sec_ntlmssp = true;
1222         }
1223
1224         rc = cifs_enable_signing(server, ses->sign);
1225         if (rc)
1226                 goto neg_exit;
1227         if (blob_length) {
1228                 rc = decode_negTokenInit(security_blob, blob_length, server);
1229                 if (rc == 1)
1230                         rc = 0;
1231                 else if (rc == 0)
1232                         rc = -EIO;
1233         }
1234
1235         if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) {
1236                 if (rsp->NegotiateContextCount)
1237                         rc = smb311_decode_neg_context(rsp, server,
1238                                                        rsp_iov.iov_len);
1239                 else
1240                         cifs_server_dbg(VFS, "Missing expected negotiate contexts\n");
1241         }
1242 neg_exit:
1243         free_rsp_buf(resp_buftype, rsp);
1244         return rc;
1245 }
1246
1247 int smb3_validate_negotiate(const unsigned int xid, struct cifs_tcon *tcon)
1248 {
1249         int rc;
1250         struct validate_negotiate_info_req *pneg_inbuf;
1251         struct validate_negotiate_info_rsp *pneg_rsp = NULL;
1252         u32 rsplen;
1253         u32 inbuflen; /* max of 4 dialects */
1254         struct TCP_Server_Info *server = tcon->ses->server;
1255
1256         cifs_dbg(FYI, "validate negotiate\n");
1257
1258         /* In SMB3.11 preauth integrity supersedes validate negotiate */
1259         if (server->dialect == SMB311_PROT_ID)
1260                 return 0;
1261
1262         /*
1263          * validation ioctl must be signed, so no point sending this if we
1264          * can not sign it (ie are not known user).  Even if signing is not
1265          * required (enabled but not negotiated), in those cases we selectively
1266          * sign just this, the first and only signed request on a connection.
1267          * Having validation of negotiate info  helps reduce attack vectors.
1268          */
1269         if (tcon->ses->session_flags & SMB2_SESSION_FLAG_IS_GUEST)
1270                 return 0; /* validation requires signing */
1271
1272         if (tcon->ses->user_name == NULL) {
1273                 cifs_dbg(FYI, "Can't validate negotiate: null user mount\n");
1274                 return 0; /* validation requires signing */
1275         }
1276
1277         if (tcon->ses->session_flags & SMB2_SESSION_FLAG_IS_NULL)
1278                 cifs_tcon_dbg(VFS, "Unexpected null user (anonymous) auth flag sent by server\n");
1279
1280         pneg_inbuf = kmalloc(sizeof(*pneg_inbuf), GFP_NOFS);
1281         if (!pneg_inbuf)
1282                 return -ENOMEM;
1283
1284         pneg_inbuf->Capabilities =
1285                         cpu_to_le32(server->vals->req_capabilities);
1286         if (tcon->ses->chan_max > 1)
1287                 pneg_inbuf->Capabilities |= cpu_to_le32(SMB2_GLOBAL_CAP_MULTI_CHANNEL);
1288
1289         memcpy(pneg_inbuf->Guid, server->client_guid,
1290                                         SMB2_CLIENT_GUID_SIZE);
1291
1292         if (tcon->ses->sign)
1293                 pneg_inbuf->SecurityMode =
1294                         cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
1295         else if (global_secflags & CIFSSEC_MAY_SIGN)
1296                 pneg_inbuf->SecurityMode =
1297                         cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
1298         else
1299                 pneg_inbuf->SecurityMode = 0;
1300
1301
1302         if (strcmp(server->vals->version_string,
1303                 SMB3ANY_VERSION_STRING) == 0) {
1304                 pneg_inbuf->Dialects[0] = cpu_to_le16(SMB30_PROT_ID);
1305                 pneg_inbuf->Dialects[1] = cpu_to_le16(SMB302_PROT_ID);
1306                 pneg_inbuf->Dialects[2] = cpu_to_le16(SMB311_PROT_ID);
1307                 pneg_inbuf->DialectCount = cpu_to_le16(3);
1308                 /* SMB 2.1 not included so subtract one dialect from len */
1309                 inbuflen = sizeof(*pneg_inbuf) -
1310                                 (sizeof(pneg_inbuf->Dialects[0]));
1311         } else if (strcmp(server->vals->version_string,
1312                 SMBDEFAULT_VERSION_STRING) == 0) {
1313                 pneg_inbuf->Dialects[0] = cpu_to_le16(SMB21_PROT_ID);
1314                 pneg_inbuf->Dialects[1] = cpu_to_le16(SMB30_PROT_ID);
1315                 pneg_inbuf->Dialects[2] = cpu_to_le16(SMB302_PROT_ID);
1316                 pneg_inbuf->Dialects[3] = cpu_to_le16(SMB311_PROT_ID);
1317                 pneg_inbuf->DialectCount = cpu_to_le16(4);
1318                 /* structure is big enough for 4 dialects */
1319                 inbuflen = sizeof(*pneg_inbuf);
1320         } else {
1321                 /* otherwise specific dialect was requested */
1322                 pneg_inbuf->Dialects[0] =
1323                         cpu_to_le16(server->vals->protocol_id);
1324                 pneg_inbuf->DialectCount = cpu_to_le16(1);
1325                 /* structure is big enough for 4 dialects, sending only 1 */
1326                 inbuflen = sizeof(*pneg_inbuf) -
1327                                 sizeof(pneg_inbuf->Dialects[0]) * 3;
1328         }
1329
1330         rc = SMB2_ioctl(xid, tcon, NO_FILE_ID, NO_FILE_ID,
1331                 FSCTL_VALIDATE_NEGOTIATE_INFO,
1332                 (char *)pneg_inbuf, inbuflen, CIFSMaxBufSize,
1333                 (char **)&pneg_rsp, &rsplen);
1334         if (rc == -EOPNOTSUPP) {
1335                 /*
1336                  * Old Windows versions or Netapp SMB server can return
1337                  * not supported error. Client should accept it.
1338                  */
1339                 cifs_tcon_dbg(VFS, "Server does not support validate negotiate\n");
1340                 rc = 0;
1341                 goto out_free_inbuf;
1342         } else if (rc != 0) {
1343                 cifs_tcon_dbg(VFS, "validate protocol negotiate failed: %d\n",
1344                               rc);
1345                 rc = -EIO;
1346                 goto out_free_inbuf;
1347         }
1348
1349         rc = -EIO;
1350         if (rsplen != sizeof(*pneg_rsp)) {
1351                 cifs_tcon_dbg(VFS, "Invalid protocol negotiate response size: %d\n",
1352                               rsplen);
1353
1354                 /* relax check since Mac returns max bufsize allowed on ioctl */
1355                 if (rsplen > CIFSMaxBufSize || rsplen < sizeof(*pneg_rsp))
1356                         goto out_free_rsp;
1357         }
1358
1359         /* check validate negotiate info response matches what we got earlier */
1360         if (pneg_rsp->Dialect != cpu_to_le16(server->dialect))
1361                 goto vneg_out;
1362
1363         if (pneg_rsp->SecurityMode != cpu_to_le16(server->sec_mode))
1364                 goto vneg_out;
1365
1366         /* do not validate server guid because not saved at negprot time yet */
1367
1368         if ((le32_to_cpu(pneg_rsp->Capabilities) | SMB2_NT_FIND |
1369               SMB2_LARGE_FILES) != server->capabilities)
1370                 goto vneg_out;
1371
1372         /* validate negotiate successful */
1373         rc = 0;
1374         cifs_dbg(FYI, "validate negotiate info successful\n");
1375         goto out_free_rsp;
1376
1377 vneg_out:
1378         cifs_tcon_dbg(VFS, "protocol revalidation - security settings mismatch\n");
1379 out_free_rsp:
1380         kfree(pneg_rsp);
1381 out_free_inbuf:
1382         kfree(pneg_inbuf);
1383         return rc;
1384 }
1385
1386 enum securityEnum
1387 smb2_select_sectype(struct TCP_Server_Info *server, enum securityEnum requested)
1388 {
1389         switch (requested) {
1390         case Kerberos:
1391         case RawNTLMSSP:
1392                 return requested;
1393         case NTLMv2:
1394                 return RawNTLMSSP;
1395         case Unspecified:
1396                 if (server->sec_ntlmssp &&
1397                         (global_secflags & CIFSSEC_MAY_NTLMSSP))
1398                         return RawNTLMSSP;
1399                 if ((server->sec_kerberos || server->sec_mskerberos) &&
1400                         (global_secflags & CIFSSEC_MAY_KRB5))
1401                         return Kerberos;
1402                 fallthrough;
1403         default:
1404                 return Unspecified;
1405         }
1406 }
1407
1408 struct SMB2_sess_data {
1409         unsigned int xid;
1410         struct cifs_ses *ses;
1411         struct TCP_Server_Info *server;
1412         struct nls_table *nls_cp;
1413         void (*func)(struct SMB2_sess_data *);
1414         int result;
1415         u64 previous_session;
1416
1417         /* we will send the SMB in three pieces:
1418          * a fixed length beginning part, an optional
1419          * SPNEGO blob (which can be zero length), and a
1420          * last part which will include the strings
1421          * and rest of bcc area. This allows us to avoid
1422          * a large buffer 17K allocation
1423          */
1424         int buf0_type;
1425         struct kvec iov[2];
1426 };
1427
1428 static int
1429 SMB2_sess_alloc_buffer(struct SMB2_sess_data *sess_data)
1430 {
1431         int rc;
1432         struct cifs_ses *ses = sess_data->ses;
1433         struct TCP_Server_Info *server = sess_data->server;
1434         struct smb2_sess_setup_req *req;
1435         unsigned int total_len;
1436         bool is_binding = false;
1437
1438         rc = smb2_plain_req_init(SMB2_SESSION_SETUP, NULL, server,
1439                                  (void **) &req,
1440                                  &total_len);
1441         if (rc)
1442                 return rc;
1443
1444         spin_lock(&ses->ses_lock);
1445         is_binding = (ses->ses_status == SES_GOOD);
1446         spin_unlock(&ses->ses_lock);
1447
1448         if (is_binding) {
1449                 req->hdr.SessionId = cpu_to_le64(ses->Suid);
1450                 req->hdr.Flags |= SMB2_FLAGS_SIGNED;
1451                 req->PreviousSessionId = 0;
1452                 req->Flags = SMB2_SESSION_REQ_FLAG_BINDING;
1453                 cifs_dbg(FYI, "Binding to sess id: %llx\n", ses->Suid);
1454         } else {
1455                 /* First session, not a reauthenticate */
1456                 req->hdr.SessionId = 0;
1457                 /*
1458                  * if reconnect, we need to send previous sess id
1459                  * otherwise it is 0
1460                  */
1461                 req->PreviousSessionId = cpu_to_le64(sess_data->previous_session);
1462                 req->Flags = 0; /* MBZ */
1463                 cifs_dbg(FYI, "Fresh session. Previous: %llx\n",
1464                          sess_data->previous_session);
1465         }
1466
1467         /* enough to enable echos and oplocks and one max size write */
1468         if (server->credits >= server->max_credits)
1469                 req->hdr.CreditRequest = cpu_to_le16(0);
1470         else
1471                 req->hdr.CreditRequest = cpu_to_le16(
1472                         min_t(int, server->max_credits -
1473                               server->credits, 130));
1474
1475         /* only one of SMB2 signing flags may be set in SMB2 request */
1476         if (server->sign)
1477                 req->SecurityMode = SMB2_NEGOTIATE_SIGNING_REQUIRED;
1478         else if (global_secflags & CIFSSEC_MAY_SIGN) /* one flag unlike MUST_ */
1479                 req->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED;
1480         else
1481                 req->SecurityMode = 0;
1482
1483 #ifdef CONFIG_CIFS_DFS_UPCALL
1484         req->Capabilities = cpu_to_le32(SMB2_GLOBAL_CAP_DFS);
1485 #else
1486         req->Capabilities = 0;
1487 #endif /* DFS_UPCALL */
1488
1489         req->Channel = 0; /* MBZ */
1490
1491         sess_data->iov[0].iov_base = (char *)req;
1492         /* 1 for pad */
1493         sess_data->iov[0].iov_len = total_len - 1;
1494         /*
1495          * This variable will be used to clear the buffer
1496          * allocated above in case of any error in the calling function.
1497          */
1498         sess_data->buf0_type = CIFS_SMALL_BUFFER;
1499
1500         return 0;
1501 }
1502
1503 static void
1504 SMB2_sess_free_buffer(struct SMB2_sess_data *sess_data)
1505 {
1506         struct kvec *iov = sess_data->iov;
1507
1508         /* iov[1] is already freed by caller */
1509         if (sess_data->buf0_type != CIFS_NO_BUFFER && iov[0].iov_base)
1510                 memzero_explicit(iov[0].iov_base, iov[0].iov_len);
1511
1512         free_rsp_buf(sess_data->buf0_type, iov[0].iov_base);
1513         sess_data->buf0_type = CIFS_NO_BUFFER;
1514 }
1515
1516 static int
1517 SMB2_sess_sendreceive(struct SMB2_sess_data *sess_data)
1518 {
1519         int rc;
1520         struct smb_rqst rqst;
1521         struct smb2_sess_setup_req *req = sess_data->iov[0].iov_base;
1522         struct kvec rsp_iov = { NULL, 0 };
1523
1524         /* Testing shows that buffer offset must be at location of Buffer[0] */
1525         req->SecurityBufferOffset =
1526                 cpu_to_le16(sizeof(struct smb2_sess_setup_req));
1527         req->SecurityBufferLength = cpu_to_le16(sess_data->iov[1].iov_len);
1528
1529         memset(&rqst, 0, sizeof(struct smb_rqst));
1530         rqst.rq_iov = sess_data->iov;
1531         rqst.rq_nvec = 2;
1532
1533         /* BB add code to build os and lm fields */
1534         rc = cifs_send_recv(sess_data->xid, sess_data->ses,
1535                             sess_data->server,
1536                             &rqst,
1537                             &sess_data->buf0_type,
1538                             CIFS_LOG_ERROR | CIFS_SESS_OP, &rsp_iov);
1539         cifs_small_buf_release(sess_data->iov[0].iov_base);
1540         if (rc == 0)
1541                 sess_data->ses->expired_pwd = false;
1542         else if ((rc == -EACCES) || (rc == -EKEYEXPIRED) || (rc == -EKEYREVOKED))
1543                 sess_data->ses->expired_pwd = true;
1544
1545         memcpy(&sess_data->iov[0], &rsp_iov, sizeof(struct kvec));
1546
1547         return rc;
1548 }
1549
1550 static int
1551 SMB2_sess_establish_session(struct SMB2_sess_data *sess_data)
1552 {
1553         int rc = 0;
1554         struct cifs_ses *ses = sess_data->ses;
1555         struct TCP_Server_Info *server = sess_data->server;
1556
1557         cifs_server_lock(server);
1558         if (server->ops->generate_signingkey) {
1559                 rc = server->ops->generate_signingkey(ses, server);
1560                 if (rc) {
1561                         cifs_dbg(FYI,
1562                                 "SMB3 session key generation failed\n");
1563                         cifs_server_unlock(server);
1564                         return rc;
1565                 }
1566         }
1567         if (!server->session_estab) {
1568                 server->sequence_number = 0x2;
1569                 server->session_estab = true;
1570         }
1571         cifs_server_unlock(server);
1572
1573         cifs_dbg(FYI, "SMB2/3 session established successfully\n");
1574         return rc;
1575 }
1576
1577 #ifdef CONFIG_CIFS_UPCALL
1578 static void
1579 SMB2_auth_kerberos(struct SMB2_sess_data *sess_data)
1580 {
1581         int rc;
1582         struct cifs_ses *ses = sess_data->ses;
1583         struct TCP_Server_Info *server = sess_data->server;
1584         struct cifs_spnego_msg *msg;
1585         struct key *spnego_key = NULL;
1586         struct smb2_sess_setup_rsp *rsp = NULL;
1587         bool is_binding = false;
1588
1589         rc = SMB2_sess_alloc_buffer(sess_data);
1590         if (rc)
1591                 goto out;
1592
1593         spnego_key = cifs_get_spnego_key(ses, server);
1594         if (IS_ERR(spnego_key)) {
1595                 rc = PTR_ERR(spnego_key);
1596                 if (rc == -ENOKEY)
1597                         cifs_dbg(VFS, "Verify user has a krb5 ticket and keyutils is installed\n");
1598                 spnego_key = NULL;
1599                 goto out;
1600         }
1601
1602         msg = spnego_key->payload.data[0];
1603         /*
1604          * check version field to make sure that cifs.upcall is
1605          * sending us a response in an expected form
1606          */
1607         if (msg->version != CIFS_SPNEGO_UPCALL_VERSION) {
1608                 cifs_dbg(VFS, "bad cifs.upcall version. Expected %d got %d\n",
1609                          CIFS_SPNEGO_UPCALL_VERSION, msg->version);
1610                 rc = -EKEYREJECTED;
1611                 goto out_put_spnego_key;
1612         }
1613
1614         spin_lock(&ses->ses_lock);
1615         is_binding = (ses->ses_status == SES_GOOD);
1616         spin_unlock(&ses->ses_lock);
1617
1618         /* keep session key if binding */
1619         if (!is_binding) {
1620                 kfree_sensitive(ses->auth_key.response);
1621                 ses->auth_key.response = kmemdup(msg->data, msg->sesskey_len,
1622                                                  GFP_KERNEL);
1623                 if (!ses->auth_key.response) {
1624                         cifs_dbg(VFS, "Kerberos can't allocate (%u bytes) memory\n",
1625                                  msg->sesskey_len);
1626                         rc = -ENOMEM;
1627                         goto out_put_spnego_key;
1628                 }
1629                 ses->auth_key.len = msg->sesskey_len;
1630         }
1631
1632         sess_data->iov[1].iov_base = msg->data + msg->sesskey_len;
1633         sess_data->iov[1].iov_len = msg->secblob_len;
1634
1635         rc = SMB2_sess_sendreceive(sess_data);
1636         if (rc)
1637                 goto out_put_spnego_key;
1638
1639         rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
1640         /* keep session id and flags if binding */
1641         if (!is_binding) {
1642                 ses->Suid = le64_to_cpu(rsp->hdr.SessionId);
1643                 ses->session_flags = le16_to_cpu(rsp->SessionFlags);
1644         }
1645
1646         rc = SMB2_sess_establish_session(sess_data);
1647 out_put_spnego_key:
1648         key_invalidate(spnego_key);
1649         key_put(spnego_key);
1650         if (rc) {
1651                 kfree_sensitive(ses->auth_key.response);
1652                 ses->auth_key.response = NULL;
1653                 ses->auth_key.len = 0;
1654         }
1655 out:
1656         sess_data->result = rc;
1657         sess_data->func = NULL;
1658         SMB2_sess_free_buffer(sess_data);
1659 }
1660 #else
1661 static void
1662 SMB2_auth_kerberos(struct SMB2_sess_data *sess_data)
1663 {
1664         cifs_dbg(VFS, "Kerberos negotiated but upcall support disabled!\n");
1665         sess_data->result = -EOPNOTSUPP;
1666         sess_data->func = NULL;
1667 }
1668 #endif
1669
1670 static void
1671 SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data);
1672
1673 static void
1674 SMB2_sess_auth_rawntlmssp_negotiate(struct SMB2_sess_data *sess_data)
1675 {
1676         int rc;
1677         struct cifs_ses *ses = sess_data->ses;
1678         struct TCP_Server_Info *server = sess_data->server;
1679         struct smb2_sess_setup_rsp *rsp = NULL;
1680         unsigned char *ntlmssp_blob = NULL;
1681         bool use_spnego = false; /* else use raw ntlmssp */
1682         u16 blob_length = 0;
1683         bool is_binding = false;
1684
1685         /*
1686          * If memory allocation is successful, caller of this function
1687          * frees it.
1688          */
1689         ses->ntlmssp = kmalloc(sizeof(struct ntlmssp_auth), GFP_KERNEL);
1690         if (!ses->ntlmssp) {
1691                 rc = -ENOMEM;
1692                 goto out_err;
1693         }
1694         ses->ntlmssp->sesskey_per_smbsess = true;
1695
1696         rc = SMB2_sess_alloc_buffer(sess_data);
1697         if (rc)
1698                 goto out_err;
1699
1700         rc = build_ntlmssp_smb3_negotiate_blob(&ntlmssp_blob,
1701                                           &blob_length, ses, server,
1702                                           sess_data->nls_cp);
1703         if (rc)
1704                 goto out;
1705
1706         if (use_spnego) {
1707                 /* BB eventually need to add this */
1708                 cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
1709                 rc = -EOPNOTSUPP;
1710                 goto out;
1711         }
1712         sess_data->iov[1].iov_base = ntlmssp_blob;
1713         sess_data->iov[1].iov_len = blob_length;
1714
1715         rc = SMB2_sess_sendreceive(sess_data);
1716         rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
1717
1718         /* If true, rc here is expected and not an error */
1719         if (sess_data->buf0_type != CIFS_NO_BUFFER &&
1720                 rsp->hdr.Status == STATUS_MORE_PROCESSING_REQUIRED)
1721                 rc = 0;
1722
1723         if (rc)
1724                 goto out;
1725
1726         if (offsetof(struct smb2_sess_setup_rsp, Buffer) !=
1727                         le16_to_cpu(rsp->SecurityBufferOffset)) {
1728                 cifs_dbg(VFS, "Invalid security buffer offset %d\n",
1729                         le16_to_cpu(rsp->SecurityBufferOffset));
1730                 rc = -EIO;
1731                 goto out;
1732         }
1733         rc = decode_ntlmssp_challenge(rsp->Buffer,
1734                         le16_to_cpu(rsp->SecurityBufferLength), ses);
1735         if (rc)
1736                 goto out;
1737
1738         cifs_dbg(FYI, "rawntlmssp session setup challenge phase\n");
1739
1740         spin_lock(&ses->ses_lock);
1741         is_binding = (ses->ses_status == SES_GOOD);
1742         spin_unlock(&ses->ses_lock);
1743
1744         /* keep existing ses id and flags if binding */
1745         if (!is_binding) {
1746                 ses->Suid = le64_to_cpu(rsp->hdr.SessionId);
1747                 ses->session_flags = le16_to_cpu(rsp->SessionFlags);
1748         }
1749
1750 out:
1751         kfree_sensitive(ntlmssp_blob);
1752         SMB2_sess_free_buffer(sess_data);
1753         if (!rc) {
1754                 sess_data->result = 0;
1755                 sess_data->func = SMB2_sess_auth_rawntlmssp_authenticate;
1756                 return;
1757         }
1758 out_err:
1759         kfree_sensitive(ses->ntlmssp);
1760         ses->ntlmssp = NULL;
1761         sess_data->result = rc;
1762         sess_data->func = NULL;
1763 }
1764
1765 static void
1766 SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data)
1767 {
1768         int rc;
1769         struct cifs_ses *ses = sess_data->ses;
1770         struct TCP_Server_Info *server = sess_data->server;
1771         struct smb2_sess_setup_req *req;
1772         struct smb2_sess_setup_rsp *rsp = NULL;
1773         unsigned char *ntlmssp_blob = NULL;
1774         bool use_spnego = false; /* else use raw ntlmssp */
1775         u16 blob_length = 0;
1776         bool is_binding = false;
1777
1778         rc = SMB2_sess_alloc_buffer(sess_data);
1779         if (rc)
1780                 goto out;
1781
1782         req = (struct smb2_sess_setup_req *) sess_data->iov[0].iov_base;
1783         req->hdr.SessionId = cpu_to_le64(ses->Suid);
1784
1785         rc = build_ntlmssp_auth_blob(&ntlmssp_blob, &blob_length,
1786                                      ses, server,
1787                                      sess_data->nls_cp);
1788         if (rc) {
1789                 cifs_dbg(FYI, "build_ntlmssp_auth_blob failed %d\n", rc);
1790                 goto out;
1791         }
1792
1793         if (use_spnego) {
1794                 /* BB eventually need to add this */
1795                 cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
1796                 rc = -EOPNOTSUPP;
1797                 goto out;
1798         }
1799         sess_data->iov[1].iov_base = ntlmssp_blob;
1800         sess_data->iov[1].iov_len = blob_length;
1801
1802         rc = SMB2_sess_sendreceive(sess_data);
1803         if (rc)
1804                 goto out;
1805
1806         rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
1807
1808         spin_lock(&ses->ses_lock);
1809         is_binding = (ses->ses_status == SES_GOOD);
1810         spin_unlock(&ses->ses_lock);
1811
1812         /* keep existing ses id and flags if binding */
1813         if (!is_binding) {
1814                 ses->Suid = le64_to_cpu(rsp->hdr.SessionId);
1815                 ses->session_flags = le16_to_cpu(rsp->SessionFlags);
1816         }
1817
1818         rc = SMB2_sess_establish_session(sess_data);
1819 #ifdef CONFIG_CIFS_DEBUG_DUMP_KEYS
1820         if (ses->server->dialect < SMB30_PROT_ID) {
1821                 cifs_dbg(VFS, "%s: dumping generated SMB2 session keys\n", __func__);
1822                 /*
1823                  * The session id is opaque in terms of endianness, so we can't
1824                  * print it as a long long. we dump it as we got it on the wire
1825                  */
1826                 cifs_dbg(VFS, "Session Id    %*ph\n", (int)sizeof(ses->Suid),
1827                          &ses->Suid);
1828                 cifs_dbg(VFS, "Session Key   %*ph\n",
1829                          SMB2_NTLMV2_SESSKEY_SIZE, ses->auth_key.response);
1830                 cifs_dbg(VFS, "Signing Key   %*ph\n",
1831                          SMB3_SIGN_KEY_SIZE, ses->auth_key.response);
1832         }
1833 #endif
1834 out:
1835         kfree_sensitive(ntlmssp_blob);
1836         SMB2_sess_free_buffer(sess_data);
1837         kfree_sensitive(ses->ntlmssp);
1838         ses->ntlmssp = NULL;
1839         sess_data->result = rc;
1840         sess_data->func = NULL;
1841 }
1842
1843 static int
1844 SMB2_select_sec(struct SMB2_sess_data *sess_data)
1845 {
1846         int type;
1847         struct cifs_ses *ses = sess_data->ses;
1848         struct TCP_Server_Info *server = sess_data->server;
1849
1850         type = smb2_select_sectype(server, ses->sectype);
1851         cifs_dbg(FYI, "sess setup type %d\n", type);
1852         if (type == Unspecified) {
1853                 cifs_dbg(VFS, "Unable to select appropriate authentication method!\n");
1854                 return -EINVAL;
1855         }
1856
1857         switch (type) {
1858         case Kerberos:
1859                 sess_data->func = SMB2_auth_kerberos;
1860                 break;
1861         case RawNTLMSSP:
1862                 sess_data->func = SMB2_sess_auth_rawntlmssp_negotiate;
1863                 break;
1864         default:
1865                 cifs_dbg(VFS, "secType %d not supported!\n", type);
1866                 return -EOPNOTSUPP;
1867         }
1868
1869         return 0;
1870 }
1871
1872 int
1873 SMB2_sess_setup(const unsigned int xid, struct cifs_ses *ses,
1874                 struct TCP_Server_Info *server,
1875                 const struct nls_table *nls_cp)
1876 {
1877         int rc = 0;
1878         struct SMB2_sess_data *sess_data;
1879
1880         cifs_dbg(FYI, "Session Setup\n");
1881
1882         if (!server) {
1883                 WARN(1, "%s: server is NULL!\n", __func__);
1884                 return -EIO;
1885         }
1886
1887         sess_data = kzalloc(sizeof(struct SMB2_sess_data), GFP_KERNEL);
1888         if (!sess_data)
1889                 return -ENOMEM;
1890
1891         sess_data->xid = xid;
1892         sess_data->ses = ses;
1893         sess_data->server = server;
1894         sess_data->buf0_type = CIFS_NO_BUFFER;
1895         sess_data->nls_cp = (struct nls_table *) nls_cp;
1896         sess_data->previous_session = ses->Suid;
1897
1898         rc = SMB2_select_sec(sess_data);
1899         if (rc)
1900                 goto out;
1901
1902         /*
1903          * Initialize the session hash with the server one.
1904          */
1905         memcpy(ses->preauth_sha_hash, server->preauth_sha_hash,
1906                SMB2_PREAUTH_HASH_SIZE);
1907
1908         while (sess_data->func)
1909                 sess_data->func(sess_data);
1910
1911         if ((ses->session_flags & SMB2_SESSION_FLAG_IS_GUEST) && (ses->sign))
1912                 cifs_server_dbg(VFS, "signing requested but authenticated as guest\n");
1913         rc = sess_data->result;
1914 out:
1915         kfree_sensitive(sess_data);
1916         return rc;
1917 }
1918
1919 int
1920 SMB2_logoff(const unsigned int xid, struct cifs_ses *ses)
1921 {
1922         struct smb_rqst rqst;
1923         struct smb2_logoff_req *req; /* response is also trivial struct */
1924         int rc = 0;
1925         struct TCP_Server_Info *server;
1926         int flags = 0;
1927         unsigned int total_len;
1928         struct kvec iov[1];
1929         struct kvec rsp_iov;
1930         int resp_buf_type;
1931
1932         cifs_dbg(FYI, "disconnect session %p\n", ses);
1933
1934         if (ses && (ses->server))
1935                 server = ses->server;
1936         else
1937                 return -EIO;
1938
1939         /* no need to send SMB logoff if uid already closed due to reconnect */
1940         spin_lock(&ses->chan_lock);
1941         if (CIFS_ALL_CHANS_NEED_RECONNECT(ses)) {
1942                 spin_unlock(&ses->chan_lock);
1943                 goto smb2_session_already_dead;
1944         }
1945         spin_unlock(&ses->chan_lock);
1946
1947         rc = smb2_plain_req_init(SMB2_LOGOFF, NULL, ses->server,
1948                                  (void **) &req, &total_len);
1949         if (rc)
1950                 return rc;
1951
1952          /* since no tcon, smb2_init can not do this, so do here */
1953         req->hdr.SessionId = cpu_to_le64(ses->Suid);
1954
1955         if (ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA)
1956                 flags |= CIFS_TRANSFORM_REQ;
1957         else if (server->sign)
1958                 req->hdr.Flags |= SMB2_FLAGS_SIGNED;
1959
1960         flags |= CIFS_NO_RSP_BUF;
1961
1962         iov[0].iov_base = (char *)req;
1963         iov[0].iov_len = total_len;
1964
1965         memset(&rqst, 0, sizeof(struct smb_rqst));
1966         rqst.rq_iov = iov;
1967         rqst.rq_nvec = 1;
1968
1969         rc = cifs_send_recv(xid, ses, ses->server,
1970                             &rqst, &resp_buf_type, flags, &rsp_iov);
1971         cifs_small_buf_release(req);
1972         /*
1973          * No tcon so can't do
1974          * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
1975          */
1976
1977 smb2_session_already_dead:
1978         return rc;
1979 }
1980
1981 static inline void cifs_stats_fail_inc(struct cifs_tcon *tcon, uint16_t code)
1982 {
1983         cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_failed[code]);
1984 }
1985
1986 #define MAX_SHARENAME_LENGTH (255 /* server */ + 80 /* share */ + 1 /* NULL */)
1987
1988 /* These are similar values to what Windows uses */
1989 static inline void init_copy_chunk_defaults(struct cifs_tcon *tcon)
1990 {
1991         tcon->max_chunks = 256;
1992         tcon->max_bytes_chunk = 1048576;
1993         tcon->max_bytes_copy = 16777216;
1994 }
1995
1996 int
1997 SMB2_tcon(const unsigned int xid, struct cifs_ses *ses, const char *tree,
1998           struct cifs_tcon *tcon, const struct nls_table *cp)
1999 {
2000         struct smb_rqst rqst;
2001         struct smb2_tree_connect_req *req;
2002         struct smb2_tree_connect_rsp *rsp = NULL;
2003         struct kvec iov[2];
2004         struct kvec rsp_iov = { NULL, 0 };
2005         int rc = 0;
2006         int resp_buftype;
2007         int unc_path_len;
2008         __le16 *unc_path = NULL;
2009         int flags = 0;
2010         unsigned int total_len;
2011         struct TCP_Server_Info *server = cifs_pick_channel(ses);
2012
2013         cifs_dbg(FYI, "TCON\n");
2014
2015         if (!server || !tree)
2016                 return -EIO;
2017
2018         unc_path = kmalloc(MAX_SHARENAME_LENGTH * 2, GFP_KERNEL);
2019         if (unc_path == NULL)
2020                 return -ENOMEM;
2021
2022         unc_path_len = cifs_strtoUTF16(unc_path, tree, strlen(tree), cp);
2023         if (unc_path_len <= 0) {
2024                 kfree(unc_path);
2025                 return -EINVAL;
2026         }
2027         unc_path_len *= 2;
2028
2029         /* SMB2 TREE_CONNECT request must be called with TreeId == 0 */
2030         tcon->tid = 0;
2031         atomic_set(&tcon->num_remote_opens, 0);
2032         rc = smb2_plain_req_init(SMB2_TREE_CONNECT, tcon, server,
2033                                  (void **) &req, &total_len);
2034         if (rc) {
2035                 kfree(unc_path);
2036                 return rc;
2037         }
2038
2039         if (smb3_encryption_required(tcon))
2040                 flags |= CIFS_TRANSFORM_REQ;
2041
2042         iov[0].iov_base = (char *)req;
2043         /* 1 for pad */
2044         iov[0].iov_len = total_len - 1;
2045
2046         /* Testing shows that buffer offset must be at location of Buffer[0] */
2047         req->PathOffset = cpu_to_le16(sizeof(struct smb2_tree_connect_req));
2048         req->PathLength = cpu_to_le16(unc_path_len);
2049         iov[1].iov_base = unc_path;
2050         iov[1].iov_len = unc_path_len;
2051
2052         /*
2053          * 3.11 tcon req must be signed if not encrypted. See MS-SMB2 3.2.4.1.1
2054          * unless it is guest or anonymous user. See MS-SMB2 3.2.5.3.1
2055          * (Samba servers don't always set the flag so also check if null user)
2056          */
2057         if ((server->dialect == SMB311_PROT_ID) &&
2058             !smb3_encryption_required(tcon) &&
2059             !(ses->session_flags &
2060                     (SMB2_SESSION_FLAG_IS_GUEST|SMB2_SESSION_FLAG_IS_NULL)) &&
2061             ((ses->user_name != NULL) || (ses->sectype == Kerberos)))
2062                 req->hdr.Flags |= SMB2_FLAGS_SIGNED;
2063
2064         memset(&rqst, 0, sizeof(struct smb_rqst));
2065         rqst.rq_iov = iov;
2066         rqst.rq_nvec = 2;
2067
2068         /* Need 64 for max size write so ask for more in case not there yet */
2069         if (server->credits >= server->max_credits)
2070                 req->hdr.CreditRequest = cpu_to_le16(0);
2071         else
2072                 req->hdr.CreditRequest = cpu_to_le16(
2073                         min_t(int, server->max_credits -
2074                               server->credits, 64));
2075
2076         rc = cifs_send_recv(xid, ses, server,
2077                             &rqst, &resp_buftype, flags, &rsp_iov);
2078         cifs_small_buf_release(req);
2079         rsp = (struct smb2_tree_connect_rsp *)rsp_iov.iov_base;
2080         trace_smb3_tcon(xid, tcon->tid, ses->Suid, tree, rc);
2081         if ((rc != 0) || (rsp == NULL)) {
2082                 cifs_stats_fail_inc(tcon, SMB2_TREE_CONNECT_HE);
2083                 tcon->need_reconnect = true;
2084                 goto tcon_error_exit;
2085         }
2086
2087         switch (rsp->ShareType) {
2088         case SMB2_SHARE_TYPE_DISK:
2089                 cifs_dbg(FYI, "connection to disk share\n");
2090                 break;
2091         case SMB2_SHARE_TYPE_PIPE:
2092                 tcon->pipe = true;
2093                 cifs_dbg(FYI, "connection to pipe share\n");
2094                 break;
2095         case SMB2_SHARE_TYPE_PRINT:
2096                 tcon->print = true;
2097                 cifs_dbg(FYI, "connection to printer\n");
2098                 break;
2099         default:
2100                 cifs_server_dbg(VFS, "unknown share type %d\n", rsp->ShareType);
2101                 rc = -EOPNOTSUPP;
2102                 goto tcon_error_exit;
2103         }
2104
2105         tcon->share_flags = le32_to_cpu(rsp->ShareFlags);
2106         tcon->capabilities = rsp->Capabilities; /* we keep caps little endian */
2107         tcon->maximal_access = le32_to_cpu(rsp->MaximalAccess);
2108         tcon->tid = le32_to_cpu(rsp->hdr.Id.SyncId.TreeId);
2109         strscpy(tcon->tree_name, tree, sizeof(tcon->tree_name));
2110
2111         if ((rsp->Capabilities & SMB2_SHARE_CAP_DFS) &&
2112             ((tcon->share_flags & SHI1005_FLAGS_DFS) == 0))
2113                 cifs_tcon_dbg(VFS, "DFS capability contradicts DFS flag\n");
2114
2115         if (tcon->seal &&
2116             !(server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
2117                 cifs_tcon_dbg(VFS, "Encryption is requested but not supported\n");
2118
2119         init_copy_chunk_defaults(tcon);
2120         if (server->ops->validate_negotiate)
2121                 rc = server->ops->validate_negotiate(xid, tcon);
2122         if (rc == 0) /* See MS-SMB2 2.2.10 and 3.2.5.5 */
2123                 if (tcon->share_flags & SMB2_SHAREFLAG_ISOLATED_TRANSPORT)
2124                         server->nosharesock = true;
2125 tcon_exit:
2126
2127         free_rsp_buf(resp_buftype, rsp);
2128         kfree(unc_path);
2129         return rc;
2130
2131 tcon_error_exit:
2132         if (rsp && rsp->hdr.Status == STATUS_BAD_NETWORK_NAME)
2133                 cifs_tcon_dbg(VFS, "BAD_NETWORK_NAME: %s\n", tree);
2134         goto tcon_exit;
2135 }
2136
2137 int
2138 SMB2_tdis(const unsigned int xid, struct cifs_tcon *tcon)
2139 {
2140         struct smb_rqst rqst;
2141         struct smb2_tree_disconnect_req *req; /* response is trivial */
2142         int rc = 0;
2143         struct cifs_ses *ses = tcon->ses;
2144         struct TCP_Server_Info *server = cifs_pick_channel(ses);
2145         int flags = 0;
2146         unsigned int total_len;
2147         struct kvec iov[1];
2148         struct kvec rsp_iov;
2149         int resp_buf_type;
2150
2151         cifs_dbg(FYI, "Tree Disconnect\n");
2152
2153         if (!ses || !(ses->server))
2154                 return -EIO;
2155
2156         trace_smb3_tdis_enter(xid, tcon->tid, ses->Suid, tcon->tree_name);
2157         spin_lock(&ses->chan_lock);
2158         if ((tcon->need_reconnect) ||
2159             (CIFS_ALL_CHANS_NEED_RECONNECT(tcon->ses))) {
2160                 spin_unlock(&ses->chan_lock);
2161                 return 0;
2162         }
2163         spin_unlock(&ses->chan_lock);
2164
2165         invalidate_all_cached_dirs(tcon);
2166
2167         rc = smb2_plain_req_init(SMB2_TREE_DISCONNECT, tcon, server,
2168                                  (void **) &req,
2169                                  &total_len);
2170         if (rc)
2171                 return rc;
2172
2173         if (smb3_encryption_required(tcon))
2174                 flags |= CIFS_TRANSFORM_REQ;
2175
2176         flags |= CIFS_NO_RSP_BUF;
2177
2178         iov[0].iov_base = (char *)req;
2179         iov[0].iov_len = total_len;
2180
2181         memset(&rqst, 0, sizeof(struct smb_rqst));
2182         rqst.rq_iov = iov;
2183         rqst.rq_nvec = 1;
2184
2185         rc = cifs_send_recv(xid, ses, server,
2186                             &rqst, &resp_buf_type, flags, &rsp_iov);
2187         cifs_small_buf_release(req);
2188         if (rc) {
2189                 cifs_stats_fail_inc(tcon, SMB2_TREE_DISCONNECT_HE);
2190                 trace_smb3_tdis_err(xid, tcon->tid, ses->Suid, rc);
2191         }
2192         trace_smb3_tdis_done(xid, tcon->tid, ses->Suid);
2193
2194         return rc;
2195 }
2196
2197
2198 static struct create_durable *
2199 create_durable_buf(void)
2200 {
2201         struct create_durable *buf;
2202
2203         buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL);
2204         if (!buf)
2205                 return NULL;
2206
2207         buf->ccontext.DataOffset = cpu_to_le16(offsetof
2208                                         (struct create_durable, Data));
2209         buf->ccontext.DataLength = cpu_to_le32(16);
2210         buf->ccontext.NameOffset = cpu_to_le16(offsetof
2211                                 (struct create_durable, Name));
2212         buf->ccontext.NameLength = cpu_to_le16(4);
2213         /* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DHnQ" */
2214         buf->Name[0] = 'D';
2215         buf->Name[1] = 'H';
2216         buf->Name[2] = 'n';
2217         buf->Name[3] = 'Q';
2218         return buf;
2219 }
2220
2221 static struct create_durable *
2222 create_reconnect_durable_buf(struct cifs_fid *fid)
2223 {
2224         struct create_durable *buf;
2225
2226         buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL);
2227         if (!buf)
2228                 return NULL;
2229
2230         buf->ccontext.DataOffset = cpu_to_le16(offsetof
2231                                         (struct create_durable, Data));
2232         buf->ccontext.DataLength = cpu_to_le32(16);
2233         buf->ccontext.NameOffset = cpu_to_le16(offsetof
2234                                 (struct create_durable, Name));
2235         buf->ccontext.NameLength = cpu_to_le16(4);
2236         buf->Data.Fid.PersistentFileId = fid->persistent_fid;
2237         buf->Data.Fid.VolatileFileId = fid->volatile_fid;
2238         /* SMB2_CREATE_DURABLE_HANDLE_RECONNECT is "DHnC" */
2239         buf->Name[0] = 'D';
2240         buf->Name[1] = 'H';
2241         buf->Name[2] = 'n';
2242         buf->Name[3] = 'C';
2243         return buf;
2244 }
2245
2246 static void
2247 parse_query_id_ctxt(struct create_context *cc, struct smb2_file_all_info *buf)
2248 {
2249         struct create_disk_id_rsp *pdisk_id = (struct create_disk_id_rsp *)cc;
2250
2251         cifs_dbg(FYI, "parse query id context 0x%llx 0x%llx\n",
2252                 pdisk_id->DiskFileId, pdisk_id->VolumeId);
2253         buf->IndexNumber = pdisk_id->DiskFileId;
2254 }
2255
2256 static void
2257 parse_posix_ctxt(struct create_context *cc, struct smb2_file_all_info *info,
2258                  struct create_posix_rsp *posix)
2259 {
2260         int sid_len;
2261         u8 *beg = (u8 *)cc + le16_to_cpu(cc->DataOffset);
2262         u8 *end = beg + le32_to_cpu(cc->DataLength);
2263         u8 *sid;
2264
2265         memset(posix, 0, sizeof(*posix));
2266
2267         posix->nlink = le32_to_cpu(*(__le32 *)(beg + 0));
2268         posix->reparse_tag = le32_to_cpu(*(__le32 *)(beg + 4));
2269         posix->mode = le32_to_cpu(*(__le32 *)(beg + 8));
2270
2271         sid = beg + 12;
2272         sid_len = posix_info_sid_size(sid, end);
2273         if (sid_len < 0) {
2274                 cifs_dbg(VFS, "bad owner sid in posix create response\n");
2275                 return;
2276         }
2277         memcpy(&posix->owner, sid, sid_len);
2278
2279         sid = sid + sid_len;
2280         sid_len = posix_info_sid_size(sid, end);
2281         if (sid_len < 0) {
2282                 cifs_dbg(VFS, "bad group sid in posix create response\n");
2283                 return;
2284         }
2285         memcpy(&posix->group, sid, sid_len);
2286
2287         cifs_dbg(FYI, "nlink=%d mode=%o reparse_tag=%x\n",
2288                  posix->nlink, posix->mode, posix->reparse_tag);
2289 }
2290
2291 int smb2_parse_contexts(struct TCP_Server_Info *server,
2292                         struct kvec *rsp_iov,
2293                         unsigned int *epoch,
2294                         char *lease_key, __u8 *oplock,
2295                         struct smb2_file_all_info *buf,
2296                         struct create_posix_rsp *posix)
2297 {
2298         struct smb2_create_rsp *rsp = rsp_iov->iov_base;
2299         struct create_context *cc;
2300         size_t rem, off, len;
2301         size_t doff, dlen;
2302         size_t noff, nlen;
2303         char *name;
2304         static const char smb3_create_tag_posix[] = {
2305                 0x93, 0xAD, 0x25, 0x50, 0x9C,
2306                 0xB4, 0x11, 0xE7, 0xB4, 0x23, 0x83,
2307                 0xDE, 0x96, 0x8B, 0xCD, 0x7C
2308         };
2309
2310         *oplock = 0;
2311
2312         off = le32_to_cpu(rsp->CreateContextsOffset);
2313         rem = le32_to_cpu(rsp->CreateContextsLength);
2314         if (check_add_overflow(off, rem, &len) || len > rsp_iov->iov_len)
2315                 return -EINVAL;
2316         cc = (struct create_context *)((u8 *)rsp + off);
2317
2318         /* Initialize inode number to 0 in case no valid data in qfid context */
2319         if (buf)
2320                 buf->IndexNumber = 0;
2321
2322         while (rem >= sizeof(*cc)) {
2323                 doff = le16_to_cpu(cc->DataOffset);
2324                 dlen = le32_to_cpu(cc->DataLength);
2325                 if (check_add_overflow(doff, dlen, &len) || len > rem)
2326                         return -EINVAL;
2327
2328                 noff = le16_to_cpu(cc->NameOffset);
2329                 nlen = le16_to_cpu(cc->NameLength);
2330                 if (noff + nlen > doff)
2331                         return -EINVAL;
2332
2333                 name = (char *)cc + noff;
2334                 switch (nlen) {
2335                 case 4:
2336                         if (!strncmp(name, SMB2_CREATE_REQUEST_LEASE, 4)) {
2337                                 *oplock = server->ops->parse_lease_buf(cc, epoch,
2338                                                                        lease_key);
2339                         } else if (buf &&
2340                                    !strncmp(name, SMB2_CREATE_QUERY_ON_DISK_ID, 4)) {
2341                                 parse_query_id_ctxt(cc, buf);
2342                         }
2343                         break;
2344                 case 16:
2345                         if (posix && !memcmp(name, smb3_create_tag_posix, 16))
2346                                 parse_posix_ctxt(cc, buf, posix);
2347                         break;
2348                 default:
2349                         cifs_dbg(FYI, "%s: unhandled context (nlen=%zu dlen=%zu)\n",
2350                                  __func__, nlen, dlen);
2351                         if (IS_ENABLED(CONFIG_CIFS_DEBUG2))
2352                                 cifs_dump_mem("context data: ", cc, dlen);
2353                         break;
2354                 }
2355
2356                 off = le32_to_cpu(cc->Next);
2357                 if (!off)
2358                         break;
2359                 if (check_sub_overflow(rem, off, &rem))
2360                         return -EINVAL;
2361                 cc = (struct create_context *)((u8 *)cc + off);
2362         }
2363
2364         if (rsp->OplockLevel != SMB2_OPLOCK_LEVEL_LEASE)
2365                 *oplock = rsp->OplockLevel;
2366
2367         return 0;
2368 }
2369
2370 static int
2371 add_lease_context(struct TCP_Server_Info *server,
2372                   struct smb2_create_req *req,
2373                   struct kvec *iov,
2374                   unsigned int *num_iovec, u8 *lease_key, __u8 *oplock)
2375 {
2376         unsigned int num = *num_iovec;
2377
2378         iov[num].iov_base = server->ops->create_lease_buf(lease_key, *oplock);
2379         if (iov[num].iov_base == NULL)
2380                 return -ENOMEM;
2381         iov[num].iov_len = server->vals->create_lease_size;
2382         req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
2383         *num_iovec = num + 1;
2384         return 0;
2385 }
2386
2387 static struct create_durable_v2 *
2388 create_durable_v2_buf(struct cifs_open_parms *oparms)
2389 {
2390         struct cifs_fid *pfid = oparms->fid;
2391         struct create_durable_v2 *buf;
2392
2393         buf = kzalloc(sizeof(struct create_durable_v2), GFP_KERNEL);
2394         if (!buf)
2395                 return NULL;
2396
2397         buf->ccontext.DataOffset = cpu_to_le16(offsetof
2398                                         (struct create_durable_v2, dcontext));
2399         buf->ccontext.DataLength = cpu_to_le32(sizeof(struct durable_context_v2));
2400         buf->ccontext.NameOffset = cpu_to_le16(offsetof
2401                                 (struct create_durable_v2, Name));
2402         buf->ccontext.NameLength = cpu_to_le16(4);
2403
2404         /*
2405          * NB: Handle timeout defaults to 0, which allows server to choose
2406          * (most servers default to 120 seconds) and most clients default to 0.
2407          * This can be overridden at mount ("handletimeout=") if the user wants
2408          * a different persistent (or resilient) handle timeout for all opens
2409          * on a particular SMB3 mount.
2410          */
2411         buf->dcontext.Timeout = cpu_to_le32(oparms->tcon->handle_timeout);
2412         buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
2413
2414         /* for replay, we should not overwrite the existing create guid */
2415         if (!oparms->replay) {
2416                 generate_random_uuid(buf->dcontext.CreateGuid);
2417                 memcpy(pfid->create_guid, buf->dcontext.CreateGuid, 16);
2418         } else
2419                 memcpy(buf->dcontext.CreateGuid, pfid->create_guid, 16);
2420
2421         /* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DH2Q" */
2422         buf->Name[0] = 'D';
2423         buf->Name[1] = 'H';
2424         buf->Name[2] = '2';
2425         buf->Name[3] = 'Q';
2426         return buf;
2427 }
2428
2429 static struct create_durable_handle_reconnect_v2 *
2430 create_reconnect_durable_v2_buf(struct cifs_fid *fid)
2431 {
2432         struct create_durable_handle_reconnect_v2 *buf;
2433
2434         buf = kzalloc(sizeof(struct create_durable_handle_reconnect_v2),
2435                         GFP_KERNEL);
2436         if (!buf)
2437                 return NULL;
2438
2439         buf->ccontext.DataOffset =
2440                 cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
2441                                      dcontext));
2442         buf->ccontext.DataLength =
2443                 cpu_to_le32(sizeof(struct durable_reconnect_context_v2));
2444         buf->ccontext.NameOffset =
2445                 cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
2446                             Name));
2447         buf->ccontext.NameLength = cpu_to_le16(4);
2448
2449         buf->dcontext.Fid.PersistentFileId = fid->persistent_fid;
2450         buf->dcontext.Fid.VolatileFileId = fid->volatile_fid;
2451         buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
2452         memcpy(buf->dcontext.CreateGuid, fid->create_guid, 16);
2453
2454         /* SMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2 is "DH2C" */
2455         buf->Name[0] = 'D';
2456         buf->Name[1] = 'H';
2457         buf->Name[2] = '2';
2458         buf->Name[3] = 'C';
2459         return buf;
2460 }
2461
2462 static int
2463 add_durable_v2_context(struct kvec *iov, unsigned int *num_iovec,
2464                     struct cifs_open_parms *oparms)
2465 {
2466         unsigned int num = *num_iovec;
2467
2468         iov[num].iov_base = create_durable_v2_buf(oparms);
2469         if (iov[num].iov_base == NULL)
2470                 return -ENOMEM;
2471         iov[num].iov_len = sizeof(struct create_durable_v2);
2472         *num_iovec = num + 1;
2473         return 0;
2474 }
2475
2476 static int
2477 add_durable_reconnect_v2_context(struct kvec *iov, unsigned int *num_iovec,
2478                     struct cifs_open_parms *oparms)
2479 {
2480         unsigned int num = *num_iovec;
2481
2482         /* indicate that we don't need to relock the file */
2483         oparms->reconnect = false;
2484
2485         iov[num].iov_base = create_reconnect_durable_v2_buf(oparms->fid);
2486         if (iov[num].iov_base == NULL)
2487                 return -ENOMEM;
2488         iov[num].iov_len = sizeof(struct create_durable_handle_reconnect_v2);
2489         *num_iovec = num + 1;
2490         return 0;
2491 }
2492
2493 static int
2494 add_durable_context(struct kvec *iov, unsigned int *num_iovec,
2495                     struct cifs_open_parms *oparms, bool use_persistent)
2496 {
2497         unsigned int num = *num_iovec;
2498
2499         if (use_persistent) {
2500                 if (oparms->reconnect)
2501                         return add_durable_reconnect_v2_context(iov, num_iovec,
2502                                                                 oparms);
2503                 else
2504                         return add_durable_v2_context(iov, num_iovec, oparms);
2505         }
2506
2507         if (oparms->reconnect) {
2508                 iov[num].iov_base = create_reconnect_durable_buf(oparms->fid);
2509                 /* indicate that we don't need to relock the file */
2510                 oparms->reconnect = false;
2511         } else
2512                 iov[num].iov_base = create_durable_buf();
2513         if (iov[num].iov_base == NULL)
2514                 return -ENOMEM;
2515         iov[num].iov_len = sizeof(struct create_durable);
2516         *num_iovec = num + 1;
2517         return 0;
2518 }
2519
2520 /* See MS-SMB2 2.2.13.2.7 */
2521 static struct crt_twarp_ctxt *
2522 create_twarp_buf(__u64 timewarp)
2523 {
2524         struct crt_twarp_ctxt *buf;
2525
2526         buf = kzalloc(sizeof(struct crt_twarp_ctxt), GFP_KERNEL);
2527         if (!buf)
2528                 return NULL;
2529
2530         buf->ccontext.DataOffset = cpu_to_le16(offsetof
2531                                         (struct crt_twarp_ctxt, Timestamp));
2532         buf->ccontext.DataLength = cpu_to_le32(8);
2533         buf->ccontext.NameOffset = cpu_to_le16(offsetof
2534                                 (struct crt_twarp_ctxt, Name));
2535         buf->ccontext.NameLength = cpu_to_le16(4);
2536         /* SMB2_CREATE_TIMEWARP_TOKEN is "TWrp" */
2537         buf->Name[0] = 'T';
2538         buf->Name[1] = 'W';
2539         buf->Name[2] = 'r';
2540         buf->Name[3] = 'p';
2541         buf->Timestamp = cpu_to_le64(timewarp);
2542         return buf;
2543 }
2544
2545 /* See MS-SMB2 2.2.13.2.7 */
2546 static int
2547 add_twarp_context(struct kvec *iov, unsigned int *num_iovec, __u64 timewarp)
2548 {
2549         unsigned int num = *num_iovec;
2550
2551         iov[num].iov_base = create_twarp_buf(timewarp);
2552         if (iov[num].iov_base == NULL)
2553                 return -ENOMEM;
2554         iov[num].iov_len = sizeof(struct crt_twarp_ctxt);
2555         *num_iovec = num + 1;
2556         return 0;
2557 }
2558
2559 /* See http://technet.microsoft.com/en-us/library/hh509017(v=ws.10).aspx */
2560 static void setup_owner_group_sids(char *buf)
2561 {
2562         struct owner_group_sids *sids = (struct owner_group_sids *)buf;
2563
2564         /* Populate the user ownership fields S-1-5-88-1 */
2565         sids->owner.Revision = 1;
2566         sids->owner.NumAuth = 3;
2567         sids->owner.Authority[5] = 5;
2568         sids->owner.SubAuthorities[0] = cpu_to_le32(88);
2569         sids->owner.SubAuthorities[1] = cpu_to_le32(1);
2570         sids->owner.SubAuthorities[2] = cpu_to_le32(current_fsuid().val);
2571
2572         /* Populate the group ownership fields S-1-5-88-2 */
2573         sids->group.Revision = 1;
2574         sids->group.NumAuth = 3;
2575         sids->group.Authority[5] = 5;
2576         sids->group.SubAuthorities[0] = cpu_to_le32(88);
2577         sids->group.SubAuthorities[1] = cpu_to_le32(2);
2578         sids->group.SubAuthorities[2] = cpu_to_le32(current_fsgid().val);
2579
2580         cifs_dbg(FYI, "owner S-1-5-88-1-%d, group S-1-5-88-2-%d\n", current_fsuid().val, current_fsgid().val);
2581 }
2582
2583 /* See MS-SMB2 2.2.13.2.2 and MS-DTYP 2.4.6 */
2584 static struct crt_sd_ctxt *
2585 create_sd_buf(umode_t mode, bool set_owner, unsigned int *len)
2586 {
2587         struct crt_sd_ctxt *buf;
2588         __u8 *ptr, *aclptr;
2589         unsigned int acelen, acl_size, ace_count;
2590         unsigned int owner_offset = 0;
2591         unsigned int group_offset = 0;
2592         struct smb3_acl acl = {};
2593
2594         *len = round_up(sizeof(struct crt_sd_ctxt) + (sizeof(struct cifs_ace) * 4), 8);
2595
2596         if (set_owner) {
2597                 /* sizeof(struct owner_group_sids) is already multiple of 8 so no need to round */
2598                 *len += sizeof(struct owner_group_sids);
2599         }
2600
2601         buf = kzalloc(*len, GFP_KERNEL);
2602         if (buf == NULL)
2603                 return buf;
2604
2605         ptr = (__u8 *)&buf[1];
2606         if (set_owner) {
2607                 /* offset fields are from beginning of security descriptor not of create context */
2608                 owner_offset = ptr - (__u8 *)&buf->sd;
2609                 buf->sd.OffsetOwner = cpu_to_le32(owner_offset);
2610                 group_offset = owner_offset + offsetof(struct owner_group_sids, group);
2611                 buf->sd.OffsetGroup = cpu_to_le32(group_offset);
2612
2613                 setup_owner_group_sids(ptr);
2614                 ptr += sizeof(struct owner_group_sids);
2615         } else {
2616                 buf->sd.OffsetOwner = 0;
2617                 buf->sd.OffsetGroup = 0;
2618         }
2619
2620         buf->ccontext.DataOffset = cpu_to_le16(offsetof(struct crt_sd_ctxt, sd));
2621         buf->ccontext.NameOffset = cpu_to_le16(offsetof(struct crt_sd_ctxt, Name));
2622         buf->ccontext.NameLength = cpu_to_le16(4);
2623         /* SMB2_CREATE_SD_BUFFER_TOKEN is "SecD" */
2624         buf->Name[0] = 'S';
2625         buf->Name[1] = 'e';
2626         buf->Name[2] = 'c';
2627         buf->Name[3] = 'D';
2628         buf->sd.Revision = 1;  /* Must be one see MS-DTYP 2.4.6 */
2629
2630         /*
2631          * ACL is "self relative" ie ACL is stored in contiguous block of memory
2632          * and "DP" ie the DACL is present
2633          */
2634         buf->sd.Control = cpu_to_le16(ACL_CONTROL_SR | ACL_CONTROL_DP);
2635
2636         /* offset owner, group and Sbz1 and SACL are all zero */
2637         buf->sd.OffsetDacl = cpu_to_le32(ptr - (__u8 *)&buf->sd);
2638         /* Ship the ACL for now. we will copy it into buf later. */
2639         aclptr = ptr;
2640         ptr += sizeof(struct smb3_acl);
2641
2642         /* create one ACE to hold the mode embedded in reserved special SID */
2643         acelen = setup_special_mode_ACE((struct cifs_ace *)ptr, (__u64)mode);
2644         ptr += acelen;
2645         acl_size = acelen + sizeof(struct smb3_acl);
2646         ace_count = 1;
2647
2648         if (set_owner) {
2649                 /* we do not need to reallocate buffer to add the two more ACEs. plenty of space */
2650                 acelen = setup_special_user_owner_ACE((struct cifs_ace *)ptr);
2651                 ptr += acelen;
2652                 acl_size += acelen;
2653                 ace_count += 1;
2654         }
2655
2656         /* and one more ACE to allow access for authenticated users */
2657         acelen = setup_authusers_ACE((struct cifs_ace *)ptr);
2658         ptr += acelen;
2659         acl_size += acelen;
2660         ace_count += 1;
2661
2662         acl.AclRevision = ACL_REVISION; /* See 2.4.4.1 of MS-DTYP */
2663         acl.AclSize = cpu_to_le16(acl_size);
2664         acl.AceCount = cpu_to_le16(ace_count);
2665         /* acl.Sbz1 and Sbz2 MBZ so are not set here, but initialized above */
2666         memcpy(aclptr, &acl, sizeof(struct smb3_acl));
2667
2668         buf->ccontext.DataLength = cpu_to_le32(ptr - (__u8 *)&buf->sd);
2669         *len = round_up((unsigned int)(ptr - (__u8 *)buf), 8);
2670
2671         return buf;
2672 }
2673
2674 static int
2675 add_sd_context(struct kvec *iov, unsigned int *num_iovec, umode_t mode, bool set_owner)
2676 {
2677         unsigned int num = *num_iovec;
2678         unsigned int len = 0;
2679
2680         iov[num].iov_base = create_sd_buf(mode, set_owner, &len);
2681         if (iov[num].iov_base == NULL)
2682                 return -ENOMEM;
2683         iov[num].iov_len = len;
2684         *num_iovec = num + 1;
2685         return 0;
2686 }
2687
2688 static struct crt_query_id_ctxt *
2689 create_query_id_buf(void)
2690 {
2691         struct crt_query_id_ctxt *buf;
2692
2693         buf = kzalloc(sizeof(struct crt_query_id_ctxt), GFP_KERNEL);
2694         if (!buf)
2695                 return NULL;
2696
2697         buf->ccontext.DataOffset = cpu_to_le16(0);
2698         buf->ccontext.DataLength = cpu_to_le32(0);
2699         buf->ccontext.NameOffset = cpu_to_le16(offsetof
2700                                 (struct crt_query_id_ctxt, Name));
2701         buf->ccontext.NameLength = cpu_to_le16(4);
2702         /* SMB2_CREATE_QUERY_ON_DISK_ID is "QFid" */
2703         buf->Name[0] = 'Q';
2704         buf->Name[1] = 'F';
2705         buf->Name[2] = 'i';
2706         buf->Name[3] = 'd';
2707         return buf;
2708 }
2709
2710 /* See MS-SMB2 2.2.13.2.9 */
2711 static int
2712 add_query_id_context(struct kvec *iov, unsigned int *num_iovec)
2713 {
2714         unsigned int num = *num_iovec;
2715
2716         iov[num].iov_base = create_query_id_buf();
2717         if (iov[num].iov_base == NULL)
2718                 return -ENOMEM;
2719         iov[num].iov_len = sizeof(struct crt_query_id_ctxt);
2720         *num_iovec = num + 1;
2721         return 0;
2722 }
2723
2724 static int
2725 alloc_path_with_tree_prefix(__le16 **out_path, int *out_size, int *out_len,
2726                             const char *treename, const __le16 *path)
2727 {
2728         int treename_len, path_len;
2729         struct nls_table *cp;
2730         const __le16 sep[] = {cpu_to_le16('\\'), cpu_to_le16(0x0000)};
2731
2732         /*
2733          * skip leading "\\"
2734          */
2735         treename_len = strlen(treename);
2736         if (treename_len < 2 || !(treename[0] == '\\' && treename[1] == '\\'))
2737                 return -EINVAL;
2738
2739         treename += 2;
2740         treename_len -= 2;
2741
2742         path_len = UniStrnlen((wchar_t *)path, PATH_MAX);
2743
2744         /* make room for one path separator only if @path isn't empty */
2745         *out_len = treename_len + (path[0] ? 1 : 0) + path_len;
2746
2747         /*
2748          * final path needs to be 8-byte aligned as specified in
2749          * MS-SMB2 2.2.13 SMB2 CREATE Request.
2750          */
2751         *out_size = round_up(*out_len * sizeof(__le16), 8);
2752         *out_path = kzalloc(*out_size + sizeof(__le16) /* null */, GFP_KERNEL);
2753         if (!*out_path)
2754                 return -ENOMEM;
2755
2756         cp = load_nls_default();
2757         cifs_strtoUTF16(*out_path, treename, treename_len, cp);
2758
2759         /* Do not append the separator if the path is empty */
2760         if (path[0] != cpu_to_le16(0x0000)) {
2761                 UniStrcat((wchar_t *)*out_path, (wchar_t *)sep);
2762                 UniStrcat((wchar_t *)*out_path, (wchar_t *)path);
2763         }
2764
2765         unload_nls(cp);
2766
2767         return 0;
2768 }
2769
2770 int smb311_posix_mkdir(const unsigned int xid, struct inode *inode,
2771                                umode_t mode, struct cifs_tcon *tcon,
2772                                const char *full_path,
2773                                struct cifs_sb_info *cifs_sb)
2774 {
2775         struct smb_rqst rqst;
2776         struct smb2_create_req *req;
2777         struct smb2_create_rsp *rsp = NULL;
2778         struct cifs_ses *ses = tcon->ses;
2779         struct kvec iov[3]; /* make sure at least one for each open context */
2780         struct kvec rsp_iov = {NULL, 0};
2781         int resp_buftype;
2782         int uni_path_len;
2783         __le16 *copy_path = NULL;
2784         int copy_size;
2785         int rc = 0;
2786         unsigned int n_iov = 2;
2787         __u32 file_attributes = 0;
2788         char *pc_buf = NULL;
2789         int flags = 0;
2790         unsigned int total_len;
2791         __le16 *utf16_path = NULL;
2792         struct TCP_Server_Info *server;
2793         int retries = 0, cur_sleep = 1;
2794
2795 replay_again:
2796         /* reinitialize for possible replay */
2797         flags = 0;
2798         n_iov = 2;
2799         server = cifs_pick_channel(ses);
2800
2801         cifs_dbg(FYI, "mkdir\n");
2802
2803         /* resource #1: path allocation */
2804         utf16_path = cifs_convert_path_to_utf16(full_path, cifs_sb);
2805         if (!utf16_path)
2806                 return -ENOMEM;
2807
2808         if (!ses || !server) {
2809                 rc = -EIO;
2810                 goto err_free_path;
2811         }
2812
2813         /* resource #2: request */
2814         rc = smb2_plain_req_init(SMB2_CREATE, tcon, server,
2815                                  (void **) &req, &total_len);
2816         if (rc)
2817                 goto err_free_path;
2818
2819
2820         if (smb3_encryption_required(tcon))
2821                 flags |= CIFS_TRANSFORM_REQ;
2822
2823         req->ImpersonationLevel = IL_IMPERSONATION;
2824         req->DesiredAccess = cpu_to_le32(FILE_WRITE_ATTRIBUTES);
2825         /* File attributes ignored on open (used in create though) */
2826         req->FileAttributes = cpu_to_le32(file_attributes);
2827         req->ShareAccess = FILE_SHARE_ALL_LE;
2828         req->CreateDisposition = cpu_to_le32(FILE_CREATE);
2829         req->CreateOptions = cpu_to_le32(CREATE_NOT_FILE);
2830
2831         iov[0].iov_base = (char *)req;
2832         /* -1 since last byte is buf[0] which is sent below (path) */
2833         iov[0].iov_len = total_len - 1;
2834
2835         req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req));
2836
2837         /* [MS-SMB2] 2.2.13 NameOffset:
2838          * If SMB2_FLAGS_DFS_OPERATIONS is set in the Flags field of
2839          * the SMB2 header, the file name includes a prefix that will
2840          * be processed during DFS name normalization as specified in
2841          * section 3.3.5.9. Otherwise, the file name is relative to
2842          * the share that is identified by the TreeId in the SMB2
2843          * header.
2844          */
2845         if (tcon->share_flags & SHI1005_FLAGS_DFS) {
2846                 int name_len;
2847
2848                 req->hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS;
2849                 rc = alloc_path_with_tree_prefix(&copy_path, &copy_size,
2850                                                  &name_len,
2851                                                  tcon->tree_name, utf16_path);
2852                 if (rc)
2853                         goto err_free_req;
2854
2855                 req->NameLength = cpu_to_le16(name_len * 2);
2856                 uni_path_len = copy_size;
2857                 /* free before overwriting resource */
2858                 kfree(utf16_path);
2859                 utf16_path = copy_path;
2860         } else {
2861                 uni_path_len = (2 * UniStrnlen((wchar_t *)utf16_path, PATH_MAX)) + 2;
2862                 /* MUST set path len (NameLength) to 0 opening root of share */
2863                 req->NameLength = cpu_to_le16(uni_path_len - 2);
2864                 if (uni_path_len % 8 != 0) {
2865                         copy_size = roundup(uni_path_len, 8);
2866                         copy_path = kzalloc(copy_size, GFP_KERNEL);
2867                         if (!copy_path) {
2868                                 rc = -ENOMEM;
2869                                 goto err_free_req;
2870                         }
2871                         memcpy((char *)copy_path, (const char *)utf16_path,
2872                                uni_path_len);
2873                         uni_path_len = copy_size;
2874                         /* free before overwriting resource */
2875                         kfree(utf16_path);
2876                         utf16_path = copy_path;
2877                 }
2878         }
2879
2880         iov[1].iov_len = uni_path_len;
2881         iov[1].iov_base = utf16_path;
2882         req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_NONE;
2883
2884         if (tcon->posix_extensions) {
2885                 /* resource #3: posix buf */
2886                 rc = add_posix_context(iov, &n_iov, mode);
2887                 if (rc)
2888                         goto err_free_req;
2889                 req->CreateContextsOffset = cpu_to_le32(
2890                         sizeof(struct smb2_create_req) +
2891                         iov[1].iov_len);
2892                 pc_buf = iov[n_iov-1].iov_base;
2893         }
2894
2895
2896         memset(&rqst, 0, sizeof(struct smb_rqst));
2897         rqst.rq_iov = iov;
2898         rqst.rq_nvec = n_iov;
2899
2900         /* no need to inc num_remote_opens because we close it just below */
2901         trace_smb3_posix_mkdir_enter(xid, tcon->tid, ses->Suid, full_path, CREATE_NOT_FILE,
2902                                     FILE_WRITE_ATTRIBUTES);
2903
2904         if (retries)
2905                 smb2_set_replay(server, &rqst);
2906
2907         /* resource #4: response buffer */
2908         rc = cifs_send_recv(xid, ses, server,
2909                             &rqst, &resp_buftype, flags, &rsp_iov);
2910         if (rc) {
2911                 cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
2912                 trace_smb3_posix_mkdir_err(xid, tcon->tid, ses->Suid,
2913                                            CREATE_NOT_FILE,
2914                                            FILE_WRITE_ATTRIBUTES, rc);
2915                 goto err_free_rsp_buf;
2916         }
2917
2918         /*
2919          * Although unlikely to be possible for rsp to be null and rc not set,
2920          * adding check below is slightly safer long term (and quiets Coverity
2921          * warning)
2922          */
2923         rsp = (struct smb2_create_rsp *)rsp_iov.iov_base;
2924         if (rsp == NULL) {
2925                 rc = -EIO;
2926                 kfree(pc_buf);
2927                 goto err_free_req;
2928         }
2929
2930         trace_smb3_posix_mkdir_done(xid, rsp->PersistentFileId, tcon->tid, ses->Suid,
2931                                     CREATE_NOT_FILE, FILE_WRITE_ATTRIBUTES);
2932
2933         SMB2_close(xid, tcon, rsp->PersistentFileId, rsp->VolatileFileId);
2934
2935         /* Eventually save off posix specific response info and timestaps */
2936
2937 err_free_rsp_buf:
2938         free_rsp_buf(resp_buftype, rsp);
2939         kfree(pc_buf);
2940 err_free_req:
2941         cifs_small_buf_release(req);
2942 err_free_path:
2943         kfree(utf16_path);
2944
2945         if (is_replayable_error(rc) &&
2946             smb2_should_replay(tcon, &retries, &cur_sleep))
2947                 goto replay_again;
2948
2949         return rc;
2950 }
2951
2952 int
2953 SMB2_open_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
2954                struct smb_rqst *rqst, __u8 *oplock,
2955                struct cifs_open_parms *oparms, __le16 *path)
2956 {
2957         struct smb2_create_req *req;
2958         unsigned int n_iov = 2;
2959         __u32 file_attributes = 0;
2960         int copy_size;
2961         int uni_path_len;
2962         unsigned int total_len;
2963         struct kvec *iov = rqst->rq_iov;
2964         __le16 *copy_path;
2965         int rc;
2966
2967         rc = smb2_plain_req_init(SMB2_CREATE, tcon, server,
2968                                  (void **) &req, &total_len);
2969         if (rc)
2970                 return rc;
2971
2972         iov[0].iov_base = (char *)req;
2973         /* -1 since last byte is buf[0] which is sent below (path) */
2974         iov[0].iov_len = total_len - 1;
2975
2976         if (oparms->create_options & CREATE_OPTION_READONLY)
2977                 file_attributes |= ATTR_READONLY;
2978         if (oparms->create_options & CREATE_OPTION_SPECIAL)
2979                 file_attributes |= ATTR_SYSTEM;
2980
2981         req->ImpersonationLevel = IL_IMPERSONATION;
2982         req->DesiredAccess = cpu_to_le32(oparms->desired_access);
2983         /* File attributes ignored on open (used in create though) */
2984         req->FileAttributes = cpu_to_le32(file_attributes);
2985         req->ShareAccess = FILE_SHARE_ALL_LE;
2986
2987         req->CreateDisposition = cpu_to_le32(oparms->disposition);
2988         req->CreateOptions = cpu_to_le32(oparms->create_options & CREATE_OPTIONS_MASK);
2989         req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req));
2990
2991         /* [MS-SMB2] 2.2.13 NameOffset:
2992          * If SMB2_FLAGS_DFS_OPERATIONS is set in the Flags field of
2993          * the SMB2 header, the file name includes a prefix that will
2994          * be processed during DFS name normalization as specified in
2995          * section 3.3.5.9. Otherwise, the file name is relative to
2996          * the share that is identified by the TreeId in the SMB2
2997          * header.
2998          */
2999         if (tcon->share_flags & SHI1005_FLAGS_DFS) {
3000                 int name_len;
3001
3002                 req->hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS;
3003                 rc = alloc_path_with_tree_prefix(&copy_path, &copy_size,
3004                                                  &name_len,
3005                                                  tcon->tree_name, path);
3006                 if (rc)
3007                         return rc;
3008                 req->NameLength = cpu_to_le16(name_len * 2);
3009                 uni_path_len = copy_size;
3010                 path = copy_path;
3011         } else {
3012                 uni_path_len = (2 * UniStrnlen((wchar_t *)path, PATH_MAX)) + 2;
3013                 /* MUST set path len (NameLength) to 0 opening root of share */
3014                 req->NameLength = cpu_to_le16(uni_path_len - 2);
3015                 copy_size = round_up(uni_path_len, 8);
3016                 copy_path = kzalloc(copy_size, GFP_KERNEL);
3017                 if (!copy_path)
3018                         return -ENOMEM;
3019                 memcpy((char *)copy_path, (const char *)path,
3020                        uni_path_len);
3021                 uni_path_len = copy_size;
3022                 path = copy_path;
3023         }
3024
3025         iov[1].iov_len = uni_path_len;
3026         iov[1].iov_base = path;
3027
3028         if ((!server->oplocks) || (tcon->no_lease))
3029                 *oplock = SMB2_OPLOCK_LEVEL_NONE;
3030
3031         if (!(server->capabilities & SMB2_GLOBAL_CAP_LEASING) ||
3032             *oplock == SMB2_OPLOCK_LEVEL_NONE)
3033                 req->RequestedOplockLevel = *oplock;
3034         else if (!(server->capabilities & SMB2_GLOBAL_CAP_DIRECTORY_LEASING) &&
3035                   (oparms->create_options & CREATE_NOT_FILE))
3036                 req->RequestedOplockLevel = *oplock; /* no srv lease support */
3037         else {
3038                 rc = add_lease_context(server, req, iov, &n_iov,
3039                                        oparms->fid->lease_key, oplock);
3040                 if (rc)
3041                         return rc;
3042         }
3043
3044         if (*oplock == SMB2_OPLOCK_LEVEL_BATCH) {
3045                 rc = add_durable_context(iov, &n_iov, oparms,
3046                                         tcon->use_persistent);
3047                 if (rc)
3048                         return rc;
3049         }
3050
3051         if (tcon->posix_extensions) {
3052                 rc = add_posix_context(iov, &n_iov, oparms->mode);
3053                 if (rc)
3054                         return rc;
3055         }
3056
3057         if (tcon->snapshot_time) {
3058                 cifs_dbg(FYI, "adding snapshot context\n");
3059                 rc = add_twarp_context(iov, &n_iov, tcon->snapshot_time);
3060                 if (rc)
3061                         return rc;
3062         }
3063
3064         if ((oparms->disposition != FILE_OPEN) && (oparms->cifs_sb)) {
3065                 bool set_mode;
3066                 bool set_owner;
3067
3068                 if ((oparms->cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MODE_FROM_SID) &&
3069                     (oparms->mode != ACL_NO_MODE))
3070                         set_mode = true;
3071                 else {
3072                         set_mode = false;
3073                         oparms->mode = ACL_NO_MODE;
3074                 }
3075
3076                 if (oparms->cifs_sb->mnt_cifs_flags & CIFS_MOUNT_UID_FROM_ACL)
3077                         set_owner = true;
3078                 else
3079                         set_owner = false;
3080
3081                 if (set_owner | set_mode) {
3082                         cifs_dbg(FYI, "add sd with mode 0x%x\n", oparms->mode);
3083                         rc = add_sd_context(iov, &n_iov, oparms->mode, set_owner);
3084                         if (rc)
3085                                 return rc;
3086                 }
3087         }
3088
3089         add_query_id_context(iov, &n_iov);
3090
3091         if (n_iov > 2) {
3092                 /*
3093                  * We have create contexts behind iov[1] (the file
3094                  * name), point at them from the main create request
3095                  */
3096                 req->CreateContextsOffset = cpu_to_le32(
3097                         sizeof(struct smb2_create_req) +
3098                         iov[1].iov_len);
3099                 req->CreateContextsLength = 0;
3100
3101                 for (unsigned int i = 2; i < (n_iov-1); i++) {
3102                         struct kvec *v = &iov[i];
3103                         size_t len = v->iov_len;
3104                         struct create_context *cctx =
3105                                 (struct create_context *)v->iov_base;
3106
3107                         cctx->Next = cpu_to_le32(len);
3108                         le32_add_cpu(&req->CreateContextsLength, len);
3109                 }
3110                 le32_add_cpu(&req->CreateContextsLength,
3111                              iov[n_iov-1].iov_len);
3112         }
3113
3114         rqst->rq_nvec = n_iov;
3115         return 0;
3116 }
3117
3118 /* rq_iov[0] is the request and is released by cifs_small_buf_release().
3119  * All other vectors are freed by kfree().
3120  */
3121 void
3122 SMB2_open_free(struct smb_rqst *rqst)
3123 {
3124         int i;
3125
3126         if (rqst && rqst->rq_iov) {
3127                 cifs_small_buf_release(rqst->rq_iov[0].iov_base);
3128                 for (i = 1; i < rqst->rq_nvec; i++)
3129                         if (rqst->rq_iov[i].iov_base != smb2_padding)
3130                                 kfree(rqst->rq_iov[i].iov_base);
3131         }
3132 }
3133
3134 int
3135 SMB2_open(const unsigned int xid, struct cifs_open_parms *oparms, __le16 *path,
3136           __u8 *oplock, struct smb2_file_all_info *buf,
3137           struct create_posix_rsp *posix,
3138           struct kvec *err_iov, int *buftype)
3139 {
3140         struct smb_rqst rqst;
3141         struct smb2_create_rsp *rsp = NULL;
3142         struct cifs_tcon *tcon = oparms->tcon;
3143         struct cifs_ses *ses = tcon->ses;
3144         struct TCP_Server_Info *server;
3145         struct kvec iov[SMB2_CREATE_IOV_SIZE];
3146         struct kvec rsp_iov = {NULL, 0};
3147         int resp_buftype = CIFS_NO_BUFFER;
3148         int rc = 0;
3149         int flags = 0;
3150         int retries = 0, cur_sleep = 1;
3151
3152 replay_again:
3153         /* reinitialize for possible replay */
3154         flags = 0;
3155         server = cifs_pick_channel(ses);
3156         oparms->replay = !!(retries);
3157
3158         cifs_dbg(FYI, "create/open\n");
3159         if (!ses || !server)
3160                 return -EIO;
3161
3162         if (smb3_encryption_required(tcon))
3163                 flags |= CIFS_TRANSFORM_REQ;
3164
3165         memset(&rqst, 0, sizeof(struct smb_rqst));
3166         memset(&iov, 0, sizeof(iov));
3167         rqst.rq_iov = iov;
3168         rqst.rq_nvec = SMB2_CREATE_IOV_SIZE;
3169
3170         rc = SMB2_open_init(tcon, server,
3171                             &rqst, oplock, oparms, path);
3172         if (rc)
3173                 goto creat_exit;
3174
3175         trace_smb3_open_enter(xid, tcon->tid, tcon->ses->Suid, oparms->path,
3176                 oparms->create_options, oparms->desired_access);
3177
3178         if (retries)
3179                 smb2_set_replay(server, &rqst);
3180
3181         rc = cifs_send_recv(xid, ses, server,
3182                             &rqst, &resp_buftype, flags,
3183                             &rsp_iov);
3184         rsp = (struct smb2_create_rsp *)rsp_iov.iov_base;
3185
3186         if (rc != 0) {
3187                 cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
3188                 if (err_iov && rsp) {
3189                         *err_iov = rsp_iov;
3190                         *buftype = resp_buftype;
3191                         resp_buftype = CIFS_NO_BUFFER;
3192                         rsp = NULL;
3193                 }
3194                 trace_smb3_open_err(xid, tcon->tid, ses->Suid,
3195                                     oparms->create_options, oparms->desired_access, rc);
3196                 if (rc == -EREMCHG) {
3197                         pr_warn_once("server share %s deleted\n",
3198                                      tcon->tree_name);
3199                         tcon->need_reconnect = true;
3200                 }
3201                 goto creat_exit;
3202         } else if (rsp == NULL) /* unlikely to happen, but safer to check */
3203                 goto creat_exit;
3204         else
3205                 trace_smb3_open_done(xid, rsp->PersistentFileId, tcon->tid, ses->Suid,
3206                                      oparms->create_options, oparms->desired_access);
3207
3208         atomic_inc(&tcon->num_remote_opens);
3209         oparms->fid->persistent_fid = rsp->PersistentFileId;
3210         oparms->fid->volatile_fid = rsp->VolatileFileId;
3211         oparms->fid->access = oparms->desired_access;
3212 #ifdef CONFIG_CIFS_DEBUG2
3213         oparms->fid->mid = le64_to_cpu(rsp->hdr.MessageId);
3214 #endif /* CIFS_DEBUG2 */
3215
3216         if (buf) {
3217                 buf->CreationTime = rsp->CreationTime;
3218                 buf->LastAccessTime = rsp->LastAccessTime;
3219                 buf->LastWriteTime = rsp->LastWriteTime;
3220                 buf->ChangeTime = rsp->ChangeTime;
3221                 buf->AllocationSize = rsp->AllocationSize;
3222                 buf->EndOfFile = rsp->EndofFile;
3223                 buf->Attributes = rsp->FileAttributes;
3224                 buf->NumberOfLinks = cpu_to_le32(1);
3225                 buf->DeletePending = 0;
3226         }
3227
3228
3229         rc = smb2_parse_contexts(server, &rsp_iov, &oparms->fid->epoch,
3230                                  oparms->fid->lease_key, oplock, buf, posix);
3231 creat_exit:
3232         SMB2_open_free(&rqst);
3233         free_rsp_buf(resp_buftype, rsp);
3234
3235         if (is_replayable_error(rc) &&
3236             smb2_should_replay(tcon, &retries, &cur_sleep))
3237                 goto replay_again;
3238
3239         return rc;
3240 }
3241
3242 int
3243 SMB2_ioctl_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3244                 struct smb_rqst *rqst,
3245                 u64 persistent_fid, u64 volatile_fid, u32 opcode,
3246                 char *in_data, u32 indatalen,
3247                 __u32 max_response_size)
3248 {
3249         struct smb2_ioctl_req *req;
3250         struct kvec *iov = rqst->rq_iov;
3251         unsigned int total_len;
3252         int rc;
3253         char *in_data_buf;
3254
3255         rc = smb2_ioctl_req_init(opcode, tcon, server,
3256                                  (void **) &req, &total_len);
3257         if (rc)
3258                 return rc;
3259
3260         if (indatalen) {
3261                 /*
3262                  * indatalen is usually small at a couple of bytes max, so
3263                  * just allocate through generic pool
3264                  */
3265                 in_data_buf = kmemdup(in_data, indatalen, GFP_NOFS);
3266                 if (!in_data_buf) {
3267                         cifs_small_buf_release(req);
3268                         return -ENOMEM;
3269                 }
3270         }
3271
3272         req->CtlCode = cpu_to_le32(opcode);
3273         req->PersistentFileId = persistent_fid;
3274         req->VolatileFileId = volatile_fid;
3275
3276         iov[0].iov_base = (char *)req;
3277         /*
3278          * If no input data, the size of ioctl struct in
3279          * protocol spec still includes a 1 byte data buffer,
3280          * but if input data passed to ioctl, we do not
3281          * want to double count this, so we do not send
3282          * the dummy one byte of data in iovec[0] if sending
3283          * input data (in iovec[1]).
3284          */
3285         if (indatalen) {
3286                 req->InputCount = cpu_to_le32(indatalen);
3287                 /* do not set InputOffset if no input data */
3288                 req->InputOffset =
3289                        cpu_to_le32(offsetof(struct smb2_ioctl_req, Buffer));
3290                 rqst->rq_nvec = 2;
3291                 iov[0].iov_len = total_len - 1;
3292                 iov[1].iov_base = in_data_buf;
3293                 iov[1].iov_len = indatalen;
3294         } else {
3295                 rqst->rq_nvec = 1;
3296                 iov[0].iov_len = total_len;
3297         }
3298
3299         req->OutputOffset = 0;
3300         req->OutputCount = 0; /* MBZ */
3301
3302         /*
3303          * In most cases max_response_size is set to 16K (CIFSMaxBufSize)
3304          * We Could increase default MaxOutputResponse, but that could require
3305          * more credits. Windows typically sets this smaller, but for some
3306          * ioctls it may be useful to allow server to send more. No point
3307          * limiting what the server can send as long as fits in one credit
3308          * We can not handle more than CIFS_MAX_BUF_SIZE yet but may want
3309          * to increase this limit up in the future.
3310          * Note that for snapshot queries that servers like Azure expect that
3311          * the first query be minimal size (and just used to get the number/size
3312          * of previous versions) so response size must be specified as EXACTLY
3313          * sizeof(struct snapshot_array) which is 16 when rounded up to multiple
3314          * of eight bytes.  Currently that is the only case where we set max
3315          * response size smaller.
3316          */
3317         req->MaxOutputResponse = cpu_to_le32(max_response_size);
3318         req->hdr.CreditCharge =
3319                 cpu_to_le16(DIV_ROUND_UP(max(indatalen, max_response_size),
3320                                          SMB2_MAX_BUFFER_SIZE));
3321         /* always an FSCTL (for now) */
3322         req->Flags = cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL);
3323
3324         /* validate negotiate request must be signed - see MS-SMB2 3.2.5.5 */
3325         if (opcode == FSCTL_VALIDATE_NEGOTIATE_INFO)
3326                 req->hdr.Flags |= SMB2_FLAGS_SIGNED;
3327
3328         return 0;
3329 }
3330
3331 void
3332 SMB2_ioctl_free(struct smb_rqst *rqst)
3333 {
3334         int i;
3335
3336         if (rqst && rqst->rq_iov) {
3337                 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3338                 for (i = 1; i < rqst->rq_nvec; i++)
3339                         if (rqst->rq_iov[i].iov_base != smb2_padding)
3340                                 kfree(rqst->rq_iov[i].iov_base);
3341         }
3342 }
3343
3344
3345 /*
3346  *      SMB2 IOCTL is used for both IOCTLs and FSCTLs
3347  */
3348 int
3349 SMB2_ioctl(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
3350            u64 volatile_fid, u32 opcode, char *in_data, u32 indatalen,
3351            u32 max_out_data_len, char **out_data,
3352            u32 *plen /* returned data len */)
3353 {
3354         struct smb_rqst rqst;
3355         struct smb2_ioctl_rsp *rsp = NULL;
3356         struct cifs_ses *ses;
3357         struct TCP_Server_Info *server;
3358         struct kvec iov[SMB2_IOCTL_IOV_SIZE];
3359         struct kvec rsp_iov = {NULL, 0};
3360         int resp_buftype = CIFS_NO_BUFFER;
3361         int rc = 0;
3362         int flags = 0;
3363         int retries = 0, cur_sleep = 1;
3364
3365         if (!tcon)
3366                 return -EIO;
3367
3368         ses = tcon->ses;
3369         if (!ses)
3370                 return -EIO;
3371
3372 replay_again:
3373         /* reinitialize for possible replay */
3374         flags = 0;
3375         server = cifs_pick_channel(ses);
3376
3377         if (!server)
3378                 return -EIO;
3379
3380         cifs_dbg(FYI, "SMB2 IOCTL\n");
3381
3382         if (out_data != NULL)
3383                 *out_data = NULL;
3384
3385         /* zero out returned data len, in case of error */
3386         if (plen)
3387                 *plen = 0;
3388
3389         if (smb3_encryption_required(tcon))
3390                 flags |= CIFS_TRANSFORM_REQ;
3391
3392         memset(&rqst, 0, sizeof(struct smb_rqst));
3393         memset(&iov, 0, sizeof(iov));
3394         rqst.rq_iov = iov;
3395         rqst.rq_nvec = SMB2_IOCTL_IOV_SIZE;
3396
3397         rc = SMB2_ioctl_init(tcon, server,
3398                              &rqst, persistent_fid, volatile_fid, opcode,
3399                              in_data, indatalen, max_out_data_len);
3400         if (rc)
3401                 goto ioctl_exit;
3402
3403         if (retries)
3404                 smb2_set_replay(server, &rqst);
3405
3406         rc = cifs_send_recv(xid, ses, server,
3407                             &rqst, &resp_buftype, flags,
3408                             &rsp_iov);
3409         rsp = (struct smb2_ioctl_rsp *)rsp_iov.iov_base;
3410
3411         if (rc != 0)
3412                 trace_smb3_fsctl_err(xid, persistent_fid, tcon->tid,
3413                                 ses->Suid, 0, opcode, rc);
3414
3415         if ((rc != 0) && (rc != -EINVAL) && (rc != -E2BIG)) {
3416                 cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3417                 goto ioctl_exit;
3418         } else if (rc == -EINVAL) {
3419                 if ((opcode != FSCTL_SRV_COPYCHUNK_WRITE) &&
3420                     (opcode != FSCTL_SRV_COPYCHUNK)) {
3421                         cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3422                         goto ioctl_exit;
3423                 }
3424         } else if (rc == -E2BIG) {
3425                 if (opcode != FSCTL_QUERY_ALLOCATED_RANGES) {
3426                         cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3427                         goto ioctl_exit;
3428                 }
3429         }
3430
3431         /* check if caller wants to look at return data or just return rc */
3432         if ((plen == NULL) || (out_data == NULL))
3433                 goto ioctl_exit;
3434
3435         /*
3436          * Although unlikely to be possible for rsp to be null and rc not set,
3437          * adding check below is slightly safer long term (and quiets Coverity
3438          * warning)
3439          */
3440         if (rsp == NULL) {
3441                 rc = -EIO;
3442                 goto ioctl_exit;
3443         }
3444
3445         *plen = le32_to_cpu(rsp->OutputCount);
3446
3447         /* We check for obvious errors in the output buffer length and offset */
3448         if (*plen == 0)
3449                 goto ioctl_exit; /* server returned no data */
3450         else if (*plen > rsp_iov.iov_len || *plen > 0xFF00) {
3451                 cifs_tcon_dbg(VFS, "srv returned invalid ioctl length: %d\n", *plen);
3452                 *plen = 0;
3453                 rc = -EIO;
3454                 goto ioctl_exit;
3455         }
3456
3457         if (rsp_iov.iov_len - *plen < le32_to_cpu(rsp->OutputOffset)) {
3458                 cifs_tcon_dbg(VFS, "Malformed ioctl resp: len %d offset %d\n", *plen,
3459                         le32_to_cpu(rsp->OutputOffset));
3460                 *plen = 0;
3461                 rc = -EIO;
3462                 goto ioctl_exit;
3463         }
3464
3465         *out_data = kmemdup((char *)rsp + le32_to_cpu(rsp->OutputOffset),
3466                             *plen, GFP_KERNEL);
3467         if (*out_data == NULL) {
3468                 rc = -ENOMEM;
3469                 goto ioctl_exit;
3470         }
3471
3472 ioctl_exit:
3473         SMB2_ioctl_free(&rqst);
3474         free_rsp_buf(resp_buftype, rsp);
3475
3476         if (is_replayable_error(rc) &&
3477             smb2_should_replay(tcon, &retries, &cur_sleep))
3478                 goto replay_again;
3479
3480         return rc;
3481 }
3482
3483 /*
3484  *   Individual callers to ioctl worker function follow
3485  */
3486
3487 int
3488 SMB2_set_compression(const unsigned int xid, struct cifs_tcon *tcon,
3489                      u64 persistent_fid, u64 volatile_fid)
3490 {
3491         int rc;
3492         struct  compress_ioctl fsctl_input;
3493         char *ret_data = NULL;
3494
3495         fsctl_input.CompressionState =
3496                         cpu_to_le16(COMPRESSION_FORMAT_DEFAULT);
3497
3498         rc = SMB2_ioctl(xid, tcon, persistent_fid, volatile_fid,
3499                         FSCTL_SET_COMPRESSION,
3500                         (char *)&fsctl_input /* data input */,
3501                         2 /* in data len */, CIFSMaxBufSize /* max out data */,
3502                         &ret_data /* out data */, NULL);
3503
3504         cifs_dbg(FYI, "set compression rc %d\n", rc);
3505
3506         return rc;
3507 }
3508
3509 int
3510 SMB2_close_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3511                 struct smb_rqst *rqst,
3512                 u64 persistent_fid, u64 volatile_fid, bool query_attrs)
3513 {
3514         struct smb2_close_req *req;
3515         struct kvec *iov = rqst->rq_iov;
3516         unsigned int total_len;
3517         int rc;
3518
3519         rc = smb2_plain_req_init(SMB2_CLOSE, tcon, server,
3520                                  (void **) &req, &total_len);
3521         if (rc)
3522                 return rc;
3523
3524         req->PersistentFileId = persistent_fid;
3525         req->VolatileFileId = volatile_fid;
3526         if (query_attrs)
3527                 req->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
3528         else
3529                 req->Flags = 0;
3530         iov[0].iov_base = (char *)req;
3531         iov[0].iov_len = total_len;
3532
3533         return 0;
3534 }
3535
3536 void
3537 SMB2_close_free(struct smb_rqst *rqst)
3538 {
3539         if (rqst && rqst->rq_iov)
3540                 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3541 }
3542
3543 int
3544 __SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
3545              u64 persistent_fid, u64 volatile_fid,
3546              struct smb2_file_network_open_info *pbuf)
3547 {
3548         struct smb_rqst rqst;
3549         struct smb2_close_rsp *rsp = NULL;
3550         struct cifs_ses *ses = tcon->ses;
3551         struct TCP_Server_Info *server;
3552         struct kvec iov[1];
3553         struct kvec rsp_iov;
3554         int resp_buftype = CIFS_NO_BUFFER;
3555         int rc = 0;
3556         int flags = 0;
3557         bool query_attrs = false;
3558         int retries = 0, cur_sleep = 1;
3559
3560 replay_again:
3561         /* reinitialize for possible replay */
3562         flags = 0;
3563         query_attrs = false;
3564         server = cifs_pick_channel(ses);
3565
3566         cifs_dbg(FYI, "Close\n");
3567
3568         if (!ses || !server)
3569                 return -EIO;
3570
3571         if (smb3_encryption_required(tcon))
3572                 flags |= CIFS_TRANSFORM_REQ;
3573
3574         memset(&rqst, 0, sizeof(struct smb_rqst));
3575         memset(&iov, 0, sizeof(iov));
3576         rqst.rq_iov = iov;
3577         rqst.rq_nvec = 1;
3578
3579         /* check if need to ask server to return timestamps in close response */
3580         if (pbuf)
3581                 query_attrs = true;
3582
3583         trace_smb3_close_enter(xid, persistent_fid, tcon->tid, ses->Suid);
3584         rc = SMB2_close_init(tcon, server,
3585                              &rqst, persistent_fid, volatile_fid,
3586                              query_attrs);
3587         if (rc)
3588                 goto close_exit;
3589
3590         if (retries)
3591                 smb2_set_replay(server, &rqst);
3592
3593         rc = cifs_send_recv(xid, ses, server,
3594                             &rqst, &resp_buftype, flags, &rsp_iov);
3595         rsp = (struct smb2_close_rsp *)rsp_iov.iov_base;
3596
3597         if (rc != 0) {
3598                 cifs_stats_fail_inc(tcon, SMB2_CLOSE_HE);
3599                 trace_smb3_close_err(xid, persistent_fid, tcon->tid, ses->Suid,
3600                                      rc);
3601                 goto close_exit;
3602         } else {
3603                 trace_smb3_close_done(xid, persistent_fid, tcon->tid,
3604                                       ses->Suid);
3605                 if (pbuf)
3606                         memcpy(&pbuf->network_open_info,
3607                                &rsp->network_open_info,
3608                                sizeof(pbuf->network_open_info));
3609                 atomic_dec(&tcon->num_remote_opens);
3610         }
3611
3612 close_exit:
3613         SMB2_close_free(&rqst);
3614         free_rsp_buf(resp_buftype, rsp);
3615
3616         /* retry close in a worker thread if this one is interrupted */
3617         if (is_interrupt_error(rc)) {
3618                 int tmp_rc;
3619
3620                 tmp_rc = smb2_handle_cancelled_close(tcon, persistent_fid,
3621                                                      volatile_fid);
3622                 if (tmp_rc)
3623                         cifs_dbg(VFS, "handle cancelled close fid 0x%llx returned error %d\n",
3624                                  persistent_fid, tmp_rc);
3625         }
3626
3627         if (is_replayable_error(rc) &&
3628             smb2_should_replay(tcon, &retries, &cur_sleep))
3629                 goto replay_again;
3630
3631         return rc;
3632 }
3633
3634 int
3635 SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
3636                 u64 persistent_fid, u64 volatile_fid)
3637 {
3638         return __SMB2_close(xid, tcon, persistent_fid, volatile_fid, NULL);
3639 }
3640
3641 int
3642 smb2_validate_iov(unsigned int offset, unsigned int buffer_length,
3643                   struct kvec *iov, unsigned int min_buf_size)
3644 {
3645         unsigned int smb_len = iov->iov_len;
3646         char *end_of_smb = smb_len + (char *)iov->iov_base;
3647         char *begin_of_buf = offset + (char *)iov->iov_base;
3648         char *end_of_buf = begin_of_buf + buffer_length;
3649
3650
3651         if (buffer_length < min_buf_size) {
3652                 cifs_dbg(VFS, "buffer length %d smaller than minimum size %d\n",
3653                          buffer_length, min_buf_size);
3654                 return -EINVAL;
3655         }
3656
3657         /* check if beyond RFC1001 maximum length */
3658         if ((smb_len > 0x7FFFFF) || (buffer_length > 0x7FFFFF)) {
3659                 cifs_dbg(VFS, "buffer length %d or smb length %d too large\n",
3660                          buffer_length, smb_len);
3661                 return -EINVAL;
3662         }
3663
3664         if ((begin_of_buf > end_of_smb) || (end_of_buf > end_of_smb)) {
3665                 cifs_dbg(VFS, "Invalid server response, bad offset to data\n");
3666                 return -EINVAL;
3667         }
3668
3669         return 0;
3670 }
3671
3672 /*
3673  * If SMB buffer fields are valid, copy into temporary buffer to hold result.
3674  * Caller must free buffer.
3675  */
3676 int
3677 smb2_validate_and_copy_iov(unsigned int offset, unsigned int buffer_length,
3678                            struct kvec *iov, unsigned int minbufsize,
3679                            char *data)
3680 {
3681         char *begin_of_buf = offset + (char *)iov->iov_base;
3682         int rc;
3683
3684         if (!data)
3685                 return -EINVAL;
3686
3687         rc = smb2_validate_iov(offset, buffer_length, iov, minbufsize);
3688         if (rc)
3689                 return rc;
3690
3691         memcpy(data, begin_of_buf, minbufsize);
3692
3693         return 0;
3694 }
3695
3696 int
3697 SMB2_query_info_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3698                      struct smb_rqst *rqst,
3699                      u64 persistent_fid, u64 volatile_fid,
3700                      u8 info_class, u8 info_type, u32 additional_info,
3701                      size_t output_len, size_t input_len, void *input)
3702 {
3703         struct smb2_query_info_req *req;
3704         struct kvec *iov = rqst->rq_iov;
3705         unsigned int total_len;
3706         size_t len;
3707         int rc;
3708
3709         if (unlikely(check_add_overflow(input_len, sizeof(*req), &len) ||
3710                      len > CIFSMaxBufSize))
3711                 return -EINVAL;
3712
3713         rc = smb2_plain_req_init(SMB2_QUERY_INFO, tcon, server,
3714                                  (void **) &req, &total_len);
3715         if (rc)
3716                 return rc;
3717
3718         req->InfoType = info_type;
3719         req->FileInfoClass = info_class;
3720         req->PersistentFileId = persistent_fid;
3721         req->VolatileFileId = volatile_fid;
3722         req->AdditionalInformation = cpu_to_le32(additional_info);
3723
3724         req->OutputBufferLength = cpu_to_le32(output_len);
3725         if (input_len) {
3726                 req->InputBufferLength = cpu_to_le32(input_len);
3727                 /* total_len for smb query request never close to le16 max */
3728                 req->InputBufferOffset = cpu_to_le16(total_len - 1);
3729                 memcpy(req->Buffer, input, input_len);
3730         }
3731
3732         iov[0].iov_base = (char *)req;
3733         /* 1 for Buffer */
3734         iov[0].iov_len = len;
3735         return 0;
3736 }
3737
3738 void
3739 SMB2_query_info_free(struct smb_rqst *rqst)
3740 {
3741         if (rqst && rqst->rq_iov)
3742                 cifs_buf_release(rqst->rq_iov[0].iov_base); /* request */
3743 }
3744
3745 static int
3746 query_info(const unsigned int xid, struct cifs_tcon *tcon,
3747            u64 persistent_fid, u64 volatile_fid, u8 info_class, u8 info_type,
3748            u32 additional_info, size_t output_len, size_t min_len, void **data,
3749                 u32 *dlen)
3750 {
3751         struct smb_rqst rqst;
3752         struct smb2_query_info_rsp *rsp = NULL;
3753         struct kvec iov[1];
3754         struct kvec rsp_iov;
3755         int rc = 0;
3756         int resp_buftype = CIFS_NO_BUFFER;
3757         struct cifs_ses *ses = tcon->ses;
3758         struct TCP_Server_Info *server;
3759         int flags = 0;
3760         bool allocated = false;
3761         int retries = 0, cur_sleep = 1;
3762
3763         cifs_dbg(FYI, "Query Info\n");
3764
3765         if (!ses)
3766                 return -EIO;
3767
3768 replay_again:
3769         /* reinitialize for possible replay */
3770         flags = 0;
3771         allocated = false;
3772         server = cifs_pick_channel(ses);
3773
3774         if (!server)
3775                 return -EIO;
3776
3777         if (smb3_encryption_required(tcon))
3778                 flags |= CIFS_TRANSFORM_REQ;
3779
3780         memset(&rqst, 0, sizeof(struct smb_rqst));
3781         memset(&iov, 0, sizeof(iov));
3782         rqst.rq_iov = iov;
3783         rqst.rq_nvec = 1;
3784
3785         rc = SMB2_query_info_init(tcon, server,
3786                                   &rqst, persistent_fid, volatile_fid,
3787                                   info_class, info_type, additional_info,
3788                                   output_len, 0, NULL);
3789         if (rc)
3790                 goto qinf_exit;
3791
3792         trace_smb3_query_info_enter(xid, persistent_fid, tcon->tid,
3793                                     ses->Suid, info_class, (__u32)info_type);
3794
3795         if (retries)
3796                 smb2_set_replay(server, &rqst);
3797
3798         rc = cifs_send_recv(xid, ses, server,
3799                             &rqst, &resp_buftype, flags, &rsp_iov);
3800         rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
3801
3802         if (rc) {
3803                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
3804                 trace_smb3_query_info_err(xid, persistent_fid, tcon->tid,
3805                                 ses->Suid, info_class, (__u32)info_type, rc);
3806                 goto qinf_exit;
3807         }
3808
3809         trace_smb3_query_info_done(xid, persistent_fid, tcon->tid,
3810                                 ses->Suid, info_class, (__u32)info_type);
3811
3812         if (dlen) {
3813                 *dlen = le32_to_cpu(rsp->OutputBufferLength);
3814                 if (!*data) {
3815                         *data = kmalloc(*dlen, GFP_KERNEL);
3816                         if (!*data) {
3817                                 cifs_tcon_dbg(VFS,
3818                                         "Error %d allocating memory for acl\n",
3819                                         rc);
3820                                 *dlen = 0;
3821                                 rc = -ENOMEM;
3822                                 goto qinf_exit;
3823                         }
3824                         allocated = true;
3825                 }
3826         }
3827
3828         rc = smb2_validate_and_copy_iov(le16_to_cpu(rsp->OutputBufferOffset),
3829                                         le32_to_cpu(rsp->OutputBufferLength),
3830                                         &rsp_iov, dlen ? *dlen : min_len, *data);
3831         if (rc && allocated) {
3832                 kfree(*data);
3833                 *data = NULL;
3834                 *dlen = 0;
3835         }
3836
3837 qinf_exit:
3838         SMB2_query_info_free(&rqst);
3839         free_rsp_buf(resp_buftype, rsp);
3840
3841         if (is_replayable_error(rc) &&
3842             smb2_should_replay(tcon, &retries, &cur_sleep))
3843                 goto replay_again;
3844
3845         return rc;
3846 }
3847
3848 int SMB2_query_info(const unsigned int xid, struct cifs_tcon *tcon,
3849         u64 persistent_fid, u64 volatile_fid, struct smb2_file_all_info *data)
3850 {
3851         return query_info(xid, tcon, persistent_fid, volatile_fid,
3852                           FILE_ALL_INFORMATION, SMB2_O_INFO_FILE, 0,
3853                           sizeof(struct smb2_file_all_info) + PATH_MAX * 2,
3854                           sizeof(struct smb2_file_all_info), (void **)&data,
3855                           NULL);
3856 }
3857
3858 #if 0
3859 /* currently unused, as now we are doing compounding instead (see smb311_posix_query_path_info) */
3860 int
3861 SMB311_posix_query_info(const unsigned int xid, struct cifs_tcon *tcon,
3862                 u64 persistent_fid, u64 volatile_fid, struct smb311_posix_qinfo *data, u32 *plen)
3863 {
3864         size_t output_len = sizeof(struct smb311_posix_qinfo *) +
3865                         (sizeof(struct cifs_sid) * 2) + (PATH_MAX * 2);
3866         *plen = 0;
3867
3868         return query_info(xid, tcon, persistent_fid, volatile_fid,
3869                           SMB_FIND_FILE_POSIX_INFO, SMB2_O_INFO_FILE, 0,
3870                           output_len, sizeof(struct smb311_posix_qinfo), (void **)&data, plen);
3871         /* Note caller must free "data" (passed in above). It may be allocated in query_info call */
3872 }
3873 #endif
3874
3875 int
3876 SMB2_query_acl(const unsigned int xid, struct cifs_tcon *tcon,
3877                u64 persistent_fid, u64 volatile_fid,
3878                void **data, u32 *plen, u32 extra_info)
3879 {
3880         __u32 additional_info = OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
3881                                 extra_info;
3882         *plen = 0;
3883
3884         return query_info(xid, tcon, persistent_fid, volatile_fid,
3885                           0, SMB2_O_INFO_SECURITY, additional_info,
3886                           SMB2_MAX_BUFFER_SIZE, MIN_SEC_DESC_LEN, data, plen);
3887 }
3888
3889 int
3890 SMB2_get_srv_num(const unsigned int xid, struct cifs_tcon *tcon,
3891                  u64 persistent_fid, u64 volatile_fid, __le64 *uniqueid)
3892 {
3893         return query_info(xid, tcon, persistent_fid, volatile_fid,
3894                           FILE_INTERNAL_INFORMATION, SMB2_O_INFO_FILE, 0,
3895                           sizeof(struct smb2_file_internal_info),
3896                           sizeof(struct smb2_file_internal_info),
3897                           (void **)&uniqueid, NULL);
3898 }
3899
3900 /*
3901  * CHANGE_NOTIFY Request is sent to get notifications on changes to a directory
3902  * See MS-SMB2 2.2.35 and 2.2.36
3903  */
3904
3905 static int
3906 SMB2_notify_init(const unsigned int xid, struct smb_rqst *rqst,
3907                  struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3908                  u64 persistent_fid, u64 volatile_fid,
3909                  u32 completion_filter, bool watch_tree)
3910 {
3911         struct smb2_change_notify_req *req;
3912         struct kvec *iov = rqst->rq_iov;
3913         unsigned int total_len;
3914         int rc;
3915
3916         rc = smb2_plain_req_init(SMB2_CHANGE_NOTIFY, tcon, server,
3917                                  (void **) &req, &total_len);
3918         if (rc)
3919                 return rc;
3920
3921         req->PersistentFileId = persistent_fid;
3922         req->VolatileFileId = volatile_fid;
3923         /* See note 354 of MS-SMB2, 64K max */
3924         req->OutputBufferLength =
3925                 cpu_to_le32(SMB2_MAX_BUFFER_SIZE - MAX_SMB2_HDR_SIZE);
3926         req->CompletionFilter = cpu_to_le32(completion_filter);
3927         if (watch_tree)
3928                 req->Flags = cpu_to_le16(SMB2_WATCH_TREE);
3929         else
3930                 req->Flags = 0;
3931
3932         iov[0].iov_base = (char *)req;
3933         iov[0].iov_len = total_len;
3934
3935         return 0;
3936 }
3937
3938 int
3939 SMB2_change_notify(const unsigned int xid, struct cifs_tcon *tcon,
3940                 u64 persistent_fid, u64 volatile_fid, bool watch_tree,
3941                 u32 completion_filter, u32 max_out_data_len, char **out_data,
3942                 u32 *plen /* returned data len */)
3943 {
3944         struct cifs_ses *ses = tcon->ses;
3945         struct TCP_Server_Info *server;
3946         struct smb_rqst rqst;
3947         struct smb2_change_notify_rsp *smb_rsp;
3948         struct kvec iov[1];
3949         struct kvec rsp_iov = {NULL, 0};
3950         int resp_buftype = CIFS_NO_BUFFER;
3951         int flags = 0;
3952         int rc = 0;
3953         int retries = 0, cur_sleep = 1;
3954
3955 replay_again:
3956         /* reinitialize for possible replay */
3957         flags = 0;
3958         server = cifs_pick_channel(ses);
3959
3960         cifs_dbg(FYI, "change notify\n");
3961         if (!ses || !server)
3962                 return -EIO;
3963
3964         if (smb3_encryption_required(tcon))
3965                 flags |= CIFS_TRANSFORM_REQ;
3966
3967         memset(&rqst, 0, sizeof(struct smb_rqst));
3968         memset(&iov, 0, sizeof(iov));
3969         if (plen)
3970                 *plen = 0;
3971
3972         rqst.rq_iov = iov;
3973         rqst.rq_nvec = 1;
3974
3975         rc = SMB2_notify_init(xid, &rqst, tcon, server,
3976                               persistent_fid, volatile_fid,
3977                               completion_filter, watch_tree);
3978         if (rc)
3979                 goto cnotify_exit;
3980
3981         trace_smb3_notify_enter(xid, persistent_fid, tcon->tid, ses->Suid,
3982                                 (u8)watch_tree, completion_filter);
3983
3984         if (retries)
3985                 smb2_set_replay(server, &rqst);
3986
3987         rc = cifs_send_recv(xid, ses, server,
3988                             &rqst, &resp_buftype, flags, &rsp_iov);
3989
3990         if (rc != 0) {
3991                 cifs_stats_fail_inc(tcon, SMB2_CHANGE_NOTIFY_HE);
3992                 trace_smb3_notify_err(xid, persistent_fid, tcon->tid, ses->Suid,
3993                                 (u8)watch_tree, completion_filter, rc);
3994         } else {
3995                 trace_smb3_notify_done(xid, persistent_fid, tcon->tid,
3996                         ses->Suid, (u8)watch_tree, completion_filter);
3997                 /* validate that notify information is plausible */
3998                 if ((rsp_iov.iov_base == NULL) ||
3999                     (rsp_iov.iov_len < sizeof(struct smb2_change_notify_rsp) + 1))
4000                         goto cnotify_exit;
4001
4002                 smb_rsp = (struct smb2_change_notify_rsp *)rsp_iov.iov_base;
4003
4004                 smb2_validate_iov(le16_to_cpu(smb_rsp->OutputBufferOffset),
4005                                 le32_to_cpu(smb_rsp->OutputBufferLength), &rsp_iov,
4006                                 sizeof(struct file_notify_information));
4007
4008                 *out_data = kmemdup((char *)smb_rsp + le16_to_cpu(smb_rsp->OutputBufferOffset),
4009                                 le32_to_cpu(smb_rsp->OutputBufferLength), GFP_KERNEL);
4010                 if (*out_data == NULL) {
4011                         rc = -ENOMEM;
4012                         goto cnotify_exit;
4013                 } else if (plen)
4014                         *plen = le32_to_cpu(smb_rsp->OutputBufferLength);
4015         }
4016
4017  cnotify_exit:
4018         if (rqst.rq_iov)
4019                 cifs_small_buf_release(rqst.rq_iov[0].iov_base); /* request */
4020         free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4021
4022         if (is_replayable_error(rc) &&
4023             smb2_should_replay(tcon, &retries, &cur_sleep))
4024                 goto replay_again;
4025
4026         return rc;
4027 }
4028
4029
4030
4031 /*
4032  * This is a no-op for now. We're not really interested in the reply, but
4033  * rather in the fact that the server sent one and that server->lstrp
4034  * gets updated.
4035  *
4036  * FIXME: maybe we should consider checking that the reply matches request?
4037  */
4038 static void
4039 smb2_echo_callback(struct mid_q_entry *mid)
4040 {
4041         struct TCP_Server_Info *server = mid->callback_data;
4042         struct smb2_echo_rsp *rsp = (struct smb2_echo_rsp *)mid->resp_buf;
4043         struct cifs_credits credits = { .value = 0, .instance = 0 };
4044
4045         if (mid->mid_state == MID_RESPONSE_RECEIVED
4046             || mid->mid_state == MID_RESPONSE_MALFORMED) {
4047                 credits.value = le16_to_cpu(rsp->hdr.CreditRequest);
4048                 credits.instance = server->reconnect_instance;
4049         }
4050
4051         release_mid(mid);
4052         add_credits(server, &credits, CIFS_ECHO_OP);
4053 }
4054
4055 void smb2_reconnect_server(struct work_struct *work)
4056 {
4057         struct TCP_Server_Info *server = container_of(work,
4058                                         struct TCP_Server_Info, reconnect.work);
4059         struct TCP_Server_Info *pserver;
4060         struct cifs_ses *ses, *ses2;
4061         struct cifs_tcon *tcon, *tcon2;
4062         struct list_head tmp_list, tmp_ses_list;
4063         bool ses_exist = false;
4064         bool tcon_selected = false;
4065         int rc;
4066         bool resched = false;
4067
4068         /* first check if ref count has reached 0, if not inc ref count */
4069         spin_lock(&cifs_tcp_ses_lock);
4070         if (!server->srv_count) {
4071                 spin_unlock(&cifs_tcp_ses_lock);
4072                 return;
4073         }
4074         server->srv_count++;
4075         spin_unlock(&cifs_tcp_ses_lock);
4076
4077         /* If server is a channel, select the primary channel */
4078         pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
4079
4080         /* Prevent simultaneous reconnects that can corrupt tcon->rlist list */
4081         mutex_lock(&pserver->reconnect_mutex);
4082
4083         /* if the server is marked for termination, drop the ref count here */
4084         if (server->terminate) {
4085                 cifs_put_tcp_session(server, true);
4086                 mutex_unlock(&pserver->reconnect_mutex);
4087                 return;
4088         }
4089
4090         INIT_LIST_HEAD(&tmp_list);
4091         INIT_LIST_HEAD(&tmp_ses_list);
4092         cifs_dbg(FYI, "Reconnecting tcons and channels\n");
4093
4094         spin_lock(&cifs_tcp_ses_lock);
4095         list_for_each_entry(ses, &pserver->smb_ses_list, smb_ses_list) {
4096                 spin_lock(&ses->ses_lock);
4097                 if (ses->ses_status == SES_EXITING) {
4098                         spin_unlock(&ses->ses_lock);
4099                         continue;
4100                 }
4101                 spin_unlock(&ses->ses_lock);
4102
4103                 tcon_selected = false;
4104
4105                 list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
4106                         if (tcon->need_reconnect || tcon->need_reopen_files) {
4107                                 tcon->tc_count++;
4108                                 list_add_tail(&tcon->rlist, &tmp_list);
4109                                 tcon_selected = true;
4110                         }
4111                 }
4112                 /*
4113                  * IPC has the same lifetime as its session and uses its
4114                  * refcount.
4115                  */
4116                 if (ses->tcon_ipc && ses->tcon_ipc->need_reconnect) {
4117                         list_add_tail(&ses->tcon_ipc->rlist, &tmp_list);
4118                         tcon_selected = true;
4119                         cifs_smb_ses_inc_refcount(ses);
4120                 }
4121                 /*
4122                  * handle the case where channel needs to reconnect
4123                  * binding session, but tcon is healthy (some other channel
4124                  * is active)
4125                  */
4126                 spin_lock(&ses->chan_lock);
4127                 if (!tcon_selected && cifs_chan_needs_reconnect(ses, server)) {
4128                         list_add_tail(&ses->rlist, &tmp_ses_list);
4129                         ses_exist = true;
4130                         cifs_smb_ses_inc_refcount(ses);
4131                 }
4132                 spin_unlock(&ses->chan_lock);
4133         }
4134         spin_unlock(&cifs_tcp_ses_lock);
4135
4136         list_for_each_entry_safe(tcon, tcon2, &tmp_list, rlist) {
4137                 rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon, server, true);
4138                 if (!rc)
4139                         cifs_reopen_persistent_handles(tcon);
4140                 else
4141                         resched = true;
4142                 list_del_init(&tcon->rlist);
4143                 if (tcon->ipc)
4144                         cifs_put_smb_ses(tcon->ses);
4145                 else
4146                         cifs_put_tcon(tcon);
4147         }
4148
4149         if (!ses_exist)
4150                 goto done;
4151
4152         /* allocate a dummy tcon struct used for reconnect */
4153         tcon = tcon_info_alloc(false);
4154         if (!tcon) {
4155                 resched = true;
4156                 list_for_each_entry_safe(ses, ses2, &tmp_ses_list, rlist) {
4157                         list_del_init(&ses->rlist);
4158                         cifs_put_smb_ses(ses);
4159                 }
4160                 goto done;
4161         }
4162
4163         tcon->status = TID_GOOD;
4164         tcon->retry = false;
4165         tcon->need_reconnect = false;
4166
4167         /* now reconnect sessions for necessary channels */
4168         list_for_each_entry_safe(ses, ses2, &tmp_ses_list, rlist) {
4169                 tcon->ses = ses;
4170                 rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon, server, true);
4171                 if (rc)
4172                         resched = true;
4173                 list_del_init(&ses->rlist);
4174                 cifs_put_smb_ses(ses);
4175         }
4176         tconInfoFree(tcon);
4177
4178 done:
4179         cifs_dbg(FYI, "Reconnecting tcons and channels finished\n");
4180         if (resched)
4181                 queue_delayed_work(cifsiod_wq, &server->reconnect, 2 * HZ);
4182         mutex_unlock(&pserver->reconnect_mutex);
4183
4184         /* now we can safely release srv struct */
4185         cifs_put_tcp_session(server, true);
4186 }
4187
4188 int
4189 SMB2_echo(struct TCP_Server_Info *server)
4190 {
4191         struct smb2_echo_req *req;
4192         int rc = 0;
4193         struct kvec iov[1];
4194         struct smb_rqst rqst = { .rq_iov = iov,
4195                                  .rq_nvec = 1 };
4196         unsigned int total_len;
4197
4198         cifs_dbg(FYI, "In echo request for conn_id %lld\n", server->conn_id);
4199
4200         spin_lock(&server->srv_lock);
4201         if (server->ops->need_neg &&
4202             server->ops->need_neg(server)) {
4203                 spin_unlock(&server->srv_lock);
4204                 /* No need to send echo on newly established connections */
4205                 mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
4206                 return rc;
4207         }
4208         spin_unlock(&server->srv_lock);
4209
4210         rc = smb2_plain_req_init(SMB2_ECHO, NULL, server,
4211                                  (void **)&req, &total_len);
4212         if (rc)
4213                 return rc;
4214
4215         req->hdr.CreditRequest = cpu_to_le16(1);
4216
4217         iov[0].iov_len = total_len;
4218         iov[0].iov_base = (char *)req;
4219
4220         rc = cifs_call_async(server, &rqst, NULL, smb2_echo_callback, NULL,
4221                              server, CIFS_ECHO_OP, NULL);
4222         if (rc)
4223                 cifs_dbg(FYI, "Echo request failed: %d\n", rc);
4224
4225         cifs_small_buf_release(req);
4226         return rc;
4227 }
4228
4229 void
4230 SMB2_flush_free(struct smb_rqst *rqst)
4231 {
4232         if (rqst && rqst->rq_iov)
4233                 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
4234 }
4235
4236 int
4237 SMB2_flush_init(const unsigned int xid, struct smb_rqst *rqst,
4238                 struct cifs_tcon *tcon, struct TCP_Server_Info *server,
4239                 u64 persistent_fid, u64 volatile_fid)
4240 {
4241         struct smb2_flush_req *req;
4242         struct kvec *iov = rqst->rq_iov;
4243         unsigned int total_len;
4244         int rc;
4245
4246         rc = smb2_plain_req_init(SMB2_FLUSH, tcon, server,
4247                                  (void **) &req, &total_len);
4248         if (rc)
4249                 return rc;
4250
4251         req->PersistentFileId = persistent_fid;
4252         req->VolatileFileId = volatile_fid;
4253
4254         iov[0].iov_base = (char *)req;
4255         iov[0].iov_len = total_len;
4256
4257         return 0;
4258 }
4259
4260 int
4261 SMB2_flush(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
4262            u64 volatile_fid)
4263 {
4264         struct cifs_ses *ses = tcon->ses;
4265         struct smb_rqst rqst;
4266         struct kvec iov[1];
4267         struct kvec rsp_iov = {NULL, 0};
4268         struct TCP_Server_Info *server;
4269         int resp_buftype = CIFS_NO_BUFFER;
4270         int flags = 0;
4271         int rc = 0;
4272         int retries = 0, cur_sleep = 1;
4273
4274 replay_again:
4275         /* reinitialize for possible replay */
4276         flags = 0;
4277         server = cifs_pick_channel(ses);
4278
4279         cifs_dbg(FYI, "flush\n");
4280         if (!ses || !(ses->server))
4281                 return -EIO;
4282
4283         if (smb3_encryption_required(tcon))
4284                 flags |= CIFS_TRANSFORM_REQ;
4285
4286         memset(&rqst, 0, sizeof(struct smb_rqst));
4287         memset(&iov, 0, sizeof(iov));
4288         rqst.rq_iov = iov;
4289         rqst.rq_nvec = 1;
4290
4291         rc = SMB2_flush_init(xid, &rqst, tcon, server,
4292                              persistent_fid, volatile_fid);
4293         if (rc)
4294                 goto flush_exit;
4295
4296         trace_smb3_flush_enter(xid, persistent_fid, tcon->tid, ses->Suid);
4297
4298         if (retries)
4299                 smb2_set_replay(server, &rqst);
4300
4301         rc = cifs_send_recv(xid, ses, server,
4302                             &rqst, &resp_buftype, flags, &rsp_iov);
4303
4304         if (rc != 0) {
4305                 cifs_stats_fail_inc(tcon, SMB2_FLUSH_HE);
4306                 trace_smb3_flush_err(xid, persistent_fid, tcon->tid, ses->Suid,
4307                                      rc);
4308         } else
4309                 trace_smb3_flush_done(xid, persistent_fid, tcon->tid,
4310                                       ses->Suid);
4311
4312  flush_exit:
4313         SMB2_flush_free(&rqst);
4314         free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4315
4316         if (is_replayable_error(rc) &&
4317             smb2_should_replay(tcon, &retries, &cur_sleep))
4318                 goto replay_again;
4319
4320         return rc;
4321 }
4322
4323 #ifdef CONFIG_CIFS_SMB_DIRECT
4324 static inline bool smb3_use_rdma_offload(struct cifs_io_parms *io_parms)
4325 {
4326         struct TCP_Server_Info *server = io_parms->server;
4327         struct cifs_tcon *tcon = io_parms->tcon;
4328
4329         /* we can only offload if we're connected */
4330         if (!server || !tcon)
4331                 return false;
4332
4333         /* we can only offload on an rdma connection */
4334         if (!server->rdma || !server->smbd_conn)
4335                 return false;
4336
4337         /* we don't support signed offload yet */
4338         if (server->sign)
4339                 return false;
4340
4341         /* we don't support encrypted offload yet */
4342         if (smb3_encryption_required(tcon))
4343                 return false;
4344
4345         /* offload also has its overhead, so only do it if desired */
4346         if (io_parms->length < server->smbd_conn->rdma_readwrite_threshold)
4347                 return false;
4348
4349         return true;
4350 }
4351 #endif /* CONFIG_CIFS_SMB_DIRECT */
4352
4353 /*
4354  * To form a chain of read requests, any read requests after the first should
4355  * have the end_of_chain boolean set to true.
4356  */
4357 static int
4358 smb2_new_read_req(void **buf, unsigned int *total_len,
4359         struct cifs_io_parms *io_parms, struct cifs_readdata *rdata,
4360         unsigned int remaining_bytes, int request_type)
4361 {
4362         int rc = -EACCES;
4363         struct smb2_read_req *req = NULL;
4364         struct smb2_hdr *shdr;
4365         struct TCP_Server_Info *server = io_parms->server;
4366
4367         rc = smb2_plain_req_init(SMB2_READ, io_parms->tcon, server,
4368                                  (void **) &req, total_len);
4369         if (rc)
4370                 return rc;
4371
4372         if (server == NULL)
4373                 return -ECONNABORTED;
4374
4375         shdr = &req->hdr;
4376         shdr->Id.SyncId.ProcessId = cpu_to_le32(io_parms->pid);
4377
4378         req->PersistentFileId = io_parms->persistent_fid;
4379         req->VolatileFileId = io_parms->volatile_fid;
4380         req->ReadChannelInfoOffset = 0; /* reserved */
4381         req->ReadChannelInfoLength = 0; /* reserved */
4382         req->Channel = 0; /* reserved */
4383         req->MinimumCount = 0;
4384         req->Length = cpu_to_le32(io_parms->length);
4385         req->Offset = cpu_to_le64(io_parms->offset);
4386
4387         trace_smb3_read_enter(0 /* xid */,
4388                         io_parms->persistent_fid,
4389                         io_parms->tcon->tid, io_parms->tcon->ses->Suid,
4390                         io_parms->offset, io_parms->length);
4391 #ifdef CONFIG_CIFS_SMB_DIRECT
4392         /*
4393          * If we want to do a RDMA write, fill in and append
4394          * smbd_buffer_descriptor_v1 to the end of read request
4395          */
4396         if (smb3_use_rdma_offload(io_parms)) {
4397                 struct smbd_buffer_descriptor_v1 *v1;
4398                 bool need_invalidate = server->dialect == SMB30_PROT_ID;
4399
4400                 rdata->mr = smbd_register_mr(server->smbd_conn, &rdata->iter,
4401                                              true, need_invalidate);
4402                 if (!rdata->mr)
4403                         return -EAGAIN;
4404
4405                 req->Channel = SMB2_CHANNEL_RDMA_V1_INVALIDATE;
4406                 if (need_invalidate)
4407                         req->Channel = SMB2_CHANNEL_RDMA_V1;
4408                 req->ReadChannelInfoOffset =
4409                         cpu_to_le16(offsetof(struct smb2_read_req, Buffer));
4410                 req->ReadChannelInfoLength =
4411                         cpu_to_le16(sizeof(struct smbd_buffer_descriptor_v1));
4412                 v1 = (struct smbd_buffer_descriptor_v1 *) &req->Buffer[0];
4413                 v1->offset = cpu_to_le64(rdata->mr->mr->iova);
4414                 v1->token = cpu_to_le32(rdata->mr->mr->rkey);
4415                 v1->length = cpu_to_le32(rdata->mr->mr->length);
4416
4417                 *total_len += sizeof(*v1) - 1;
4418         }
4419 #endif
4420         if (request_type & CHAINED_REQUEST) {
4421                 if (!(request_type & END_OF_CHAIN)) {
4422                         /* next 8-byte aligned request */
4423                         *total_len = ALIGN(*total_len, 8);
4424                         shdr->NextCommand = cpu_to_le32(*total_len);
4425                 } else /* END_OF_CHAIN */
4426                         shdr->NextCommand = 0;
4427                 if (request_type & RELATED_REQUEST) {
4428                         shdr->Flags |= SMB2_FLAGS_RELATED_OPERATIONS;
4429                         /*
4430                          * Related requests use info from previous read request
4431                          * in chain.
4432                          */
4433                         shdr->SessionId = cpu_to_le64(0xFFFFFFFFFFFFFFFF);
4434                         shdr->Id.SyncId.TreeId = cpu_to_le32(0xFFFFFFFF);
4435                         req->PersistentFileId = (u64)-1;
4436                         req->VolatileFileId = (u64)-1;
4437                 }
4438         }
4439         if (remaining_bytes > io_parms->length)
4440                 req->RemainingBytes = cpu_to_le32(remaining_bytes);
4441         else
4442                 req->RemainingBytes = 0;
4443
4444         *buf = req;
4445         return rc;
4446 }
4447
4448 static void
4449 smb2_readv_callback(struct mid_q_entry *mid)
4450 {
4451         struct cifs_readdata *rdata = mid->callback_data;
4452         struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink);
4453         struct TCP_Server_Info *server = rdata->server;
4454         struct smb2_hdr *shdr =
4455                                 (struct smb2_hdr *)rdata->iov[0].iov_base;
4456         struct cifs_credits credits = { .value = 0, .instance = 0 };
4457         struct smb_rqst rqst = { .rq_iov = &rdata->iov[1], .rq_nvec = 1 };
4458
4459         if (rdata->got_bytes) {
4460                 rqst.rq_iter      = rdata->iter;
4461                 rqst.rq_iter_size = iov_iter_count(&rdata->iter);
4462         }
4463
4464         WARN_ONCE(rdata->server != mid->server,
4465                   "rdata server %p != mid server %p",
4466                   rdata->server, mid->server);
4467
4468         cifs_dbg(FYI, "%s: mid=%llu state=%d result=%d bytes=%u\n",
4469                  __func__, mid->mid, mid->mid_state, rdata->result,
4470                  rdata->bytes);
4471
4472         switch (mid->mid_state) {
4473         case MID_RESPONSE_RECEIVED:
4474                 credits.value = le16_to_cpu(shdr->CreditRequest);
4475                 credits.instance = server->reconnect_instance;
4476                 /* result already set, check signature */
4477                 if (server->sign && !mid->decrypted) {
4478                         int rc;
4479
4480                         iov_iter_revert(&rqst.rq_iter, rdata->got_bytes);
4481                         iov_iter_truncate(&rqst.rq_iter, rdata->got_bytes);
4482                         rc = smb2_verify_signature(&rqst, server);
4483                         if (rc)
4484                                 cifs_tcon_dbg(VFS, "SMB signature verification returned error = %d\n",
4485                                          rc);
4486                 }
4487                 /* FIXME: should this be counted toward the initiating task? */
4488                 task_io_account_read(rdata->got_bytes);
4489                 cifs_stats_bytes_read(tcon, rdata->got_bytes);
4490                 break;
4491         case MID_REQUEST_SUBMITTED:
4492         case MID_RETRY_NEEDED:
4493                 rdata->result = -EAGAIN;
4494                 if (server->sign && rdata->got_bytes)
4495                         /* reset bytes number since we can not check a sign */
4496                         rdata->got_bytes = 0;
4497                 /* FIXME: should this be counted toward the initiating task? */
4498                 task_io_account_read(rdata->got_bytes);
4499                 cifs_stats_bytes_read(tcon, rdata->got_bytes);
4500                 break;
4501         case MID_RESPONSE_MALFORMED:
4502                 credits.value = le16_to_cpu(shdr->CreditRequest);
4503                 credits.instance = server->reconnect_instance;
4504                 fallthrough;
4505         default:
4506                 rdata->result = -EIO;
4507         }
4508 #ifdef CONFIG_CIFS_SMB_DIRECT
4509         /*
4510          * If this rdata has a memmory registered, the MR can be freed
4511          * MR needs to be freed as soon as I/O finishes to prevent deadlock
4512          * because they have limited number and are used for future I/Os
4513          */
4514         if (rdata->mr) {
4515                 smbd_deregister_mr(rdata->mr);
4516                 rdata->mr = NULL;
4517         }
4518 #endif
4519         if (rdata->result && rdata->result != -ENODATA) {
4520                 cifs_stats_fail_inc(tcon, SMB2_READ_HE);
4521                 trace_smb3_read_err(0 /* xid */,
4522                                     rdata->cfile->fid.persistent_fid,
4523                                     tcon->tid, tcon->ses->Suid, rdata->offset,
4524                                     rdata->bytes, rdata->result);
4525         } else
4526                 trace_smb3_read_done(0 /* xid */,
4527                                      rdata->cfile->fid.persistent_fid,
4528                                      tcon->tid, tcon->ses->Suid,
4529                                      rdata->offset, rdata->got_bytes);
4530
4531         queue_work(cifsiod_wq, &rdata->work);
4532         release_mid(mid);
4533         add_credits(server, &credits, 0);
4534 }
4535
4536 /* smb2_async_readv - send an async read, and set up mid to handle result */
4537 int
4538 smb2_async_readv(struct cifs_readdata *rdata)
4539 {
4540         int rc, flags = 0;
4541         char *buf;
4542         struct smb2_hdr *shdr;
4543         struct cifs_io_parms io_parms;
4544         struct smb_rqst rqst = { .rq_iov = rdata->iov,
4545                                  .rq_nvec = 1 };
4546         struct TCP_Server_Info *server;
4547         struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink);
4548         unsigned int total_len;
4549         int credit_request;
4550
4551         cifs_dbg(FYI, "%s: offset=%llu bytes=%u\n",
4552                  __func__, rdata->offset, rdata->bytes);
4553
4554         if (!rdata->server)
4555                 rdata->server = cifs_pick_channel(tcon->ses);
4556
4557         io_parms.tcon = tlink_tcon(rdata->cfile->tlink);
4558         io_parms.server = server = rdata->server;
4559         io_parms.offset = rdata->offset;
4560         io_parms.length = rdata->bytes;
4561         io_parms.persistent_fid = rdata->cfile->fid.persistent_fid;
4562         io_parms.volatile_fid = rdata->cfile->fid.volatile_fid;
4563         io_parms.pid = rdata->pid;
4564
4565         rc = smb2_new_read_req(
4566                 (void **) &buf, &total_len, &io_parms, rdata, 0, 0);
4567         if (rc)
4568                 return rc;
4569
4570         if (smb3_encryption_required(io_parms.tcon))
4571                 flags |= CIFS_TRANSFORM_REQ;
4572
4573         rdata->iov[0].iov_base = buf;
4574         rdata->iov[0].iov_len = total_len;
4575
4576         shdr = (struct smb2_hdr *)buf;
4577
4578         if (rdata->credits.value > 0) {
4579                 shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(rdata->bytes,
4580                                                 SMB2_MAX_BUFFER_SIZE));
4581                 credit_request = le16_to_cpu(shdr->CreditCharge) + 8;
4582                 if (server->credits >= server->max_credits)
4583                         shdr->CreditRequest = cpu_to_le16(0);
4584                 else
4585                         shdr->CreditRequest = cpu_to_le16(
4586                                 min_t(int, server->max_credits -
4587                                                 server->credits, credit_request));
4588
4589                 rc = adjust_credits(server, &rdata->credits, rdata->bytes);
4590                 if (rc)
4591                         goto async_readv_out;
4592
4593                 flags |= CIFS_HAS_CREDITS;
4594         }
4595
4596         kref_get(&rdata->refcount);
4597         rc = cifs_call_async(server, &rqst,
4598                              cifs_readv_receive, smb2_readv_callback,
4599                              smb3_handle_read_data, rdata, flags,
4600                              &rdata->credits);
4601         if (rc) {
4602                 kref_put(&rdata->refcount, cifs_readdata_release);
4603                 cifs_stats_fail_inc(io_parms.tcon, SMB2_READ_HE);
4604                 trace_smb3_read_err(0 /* xid */, io_parms.persistent_fid,
4605                                     io_parms.tcon->tid,
4606                                     io_parms.tcon->ses->Suid,
4607                                     io_parms.offset, io_parms.length, rc);
4608         }
4609
4610 async_readv_out:
4611         cifs_small_buf_release(buf);
4612         return rc;
4613 }
4614
4615 int
4616 SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms,
4617           unsigned int *nbytes, char **buf, int *buf_type)
4618 {
4619         struct smb_rqst rqst;
4620         int resp_buftype, rc;
4621         struct smb2_read_req *req = NULL;
4622         struct smb2_read_rsp *rsp = NULL;
4623         struct kvec iov[1];
4624         struct kvec rsp_iov;
4625         unsigned int total_len;
4626         int flags = CIFS_LOG_ERROR;
4627         struct cifs_ses *ses = io_parms->tcon->ses;
4628
4629         if (!io_parms->server)
4630                 io_parms->server = cifs_pick_channel(io_parms->tcon->ses);
4631
4632         *nbytes = 0;
4633         rc = smb2_new_read_req((void **)&req, &total_len, io_parms, NULL, 0, 0);
4634         if (rc)
4635                 return rc;
4636
4637         if (smb3_encryption_required(io_parms->tcon))
4638                 flags |= CIFS_TRANSFORM_REQ;
4639
4640         iov[0].iov_base = (char *)req;
4641         iov[0].iov_len = total_len;
4642
4643         memset(&rqst, 0, sizeof(struct smb_rqst));
4644         rqst.rq_iov = iov;
4645         rqst.rq_nvec = 1;
4646
4647         rc = cifs_send_recv(xid, ses, io_parms->server,
4648                             &rqst, &resp_buftype, flags, &rsp_iov);
4649         rsp = (struct smb2_read_rsp *)rsp_iov.iov_base;
4650
4651         if (rc) {
4652                 if (rc != -ENODATA) {
4653                         cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE);
4654                         cifs_dbg(VFS, "Send error in read = %d\n", rc);
4655                         trace_smb3_read_err(xid,
4656                                             req->PersistentFileId,
4657                                             io_parms->tcon->tid, ses->Suid,
4658                                             io_parms->offset, io_parms->length,
4659                                             rc);
4660                 } else
4661                         trace_smb3_read_done(xid, req->PersistentFileId, io_parms->tcon->tid,
4662                                              ses->Suid, io_parms->offset, 0);
4663                 free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4664                 cifs_small_buf_release(req);
4665                 return rc == -ENODATA ? 0 : rc;
4666         } else
4667                 trace_smb3_read_done(xid,
4668                                     req->PersistentFileId,
4669                                     io_parms->tcon->tid, ses->Suid,
4670                                     io_parms->offset, io_parms->length);
4671
4672         cifs_small_buf_release(req);
4673
4674         *nbytes = le32_to_cpu(rsp->DataLength);
4675         if ((*nbytes > CIFS_MAX_MSGSIZE) ||
4676             (*nbytes > io_parms->length)) {
4677                 cifs_dbg(FYI, "bad length %d for count %d\n",
4678                          *nbytes, io_parms->length);
4679                 rc = -EIO;
4680                 *nbytes = 0;
4681         }
4682
4683         if (*buf) {
4684                 memcpy(*buf, (char *)rsp + rsp->DataOffset, *nbytes);
4685                 free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4686         } else if (resp_buftype != CIFS_NO_BUFFER) {
4687                 *buf = rsp_iov.iov_base;
4688                 if (resp_buftype == CIFS_SMALL_BUFFER)
4689                         *buf_type = CIFS_SMALL_BUFFER;
4690                 else if (resp_buftype == CIFS_LARGE_BUFFER)
4691                         *buf_type = CIFS_LARGE_BUFFER;
4692         }
4693         return rc;
4694 }
4695
4696 /*
4697  * Check the mid_state and signature on received buffer (if any), and queue the
4698  * workqueue completion task.
4699  */
4700 static void
4701 smb2_writev_callback(struct mid_q_entry *mid)
4702 {
4703         struct cifs_writedata *wdata = mid->callback_data;
4704         struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
4705         struct TCP_Server_Info *server = wdata->server;
4706         unsigned int written;
4707         struct smb2_write_rsp *rsp = (struct smb2_write_rsp *)mid->resp_buf;
4708         struct cifs_credits credits = { .value = 0, .instance = 0 };
4709
4710         WARN_ONCE(wdata->server != mid->server,
4711                   "wdata server %p != mid server %p",
4712                   wdata->server, mid->server);
4713
4714         switch (mid->mid_state) {
4715         case MID_RESPONSE_RECEIVED:
4716                 credits.value = le16_to_cpu(rsp->hdr.CreditRequest);
4717                 credits.instance = server->reconnect_instance;
4718                 wdata->result = smb2_check_receive(mid, server, 0);
4719                 if (wdata->result != 0)
4720                         break;
4721
4722                 written = le32_to_cpu(rsp->DataLength);
4723                 /*
4724                  * Mask off high 16 bits when bytes written as returned
4725                  * by the server is greater than bytes requested by the
4726                  * client. OS/2 servers are known to set incorrect
4727                  * CountHigh values.
4728                  */
4729                 if (written > wdata->bytes)
4730                         written &= 0xFFFF;
4731
4732                 if (written < wdata->bytes)
4733                         wdata->result = -ENOSPC;
4734                 else
4735                         wdata->bytes = written;
4736                 break;
4737         case MID_REQUEST_SUBMITTED:
4738         case MID_RETRY_NEEDED:
4739                 wdata->result = -EAGAIN;
4740                 break;
4741         case MID_RESPONSE_MALFORMED:
4742                 credits.value = le16_to_cpu(rsp->hdr.CreditRequest);
4743                 credits.instance = server->reconnect_instance;
4744                 fallthrough;
4745         default:
4746                 wdata->result = -EIO;
4747                 break;
4748         }
4749 #ifdef CONFIG_CIFS_SMB_DIRECT
4750         /*
4751          * If this wdata has a memory registered, the MR can be freed
4752          * The number of MRs available is limited, it's important to recover
4753          * used MR as soon as I/O is finished. Hold MR longer in the later
4754          * I/O process can possibly result in I/O deadlock due to lack of MR
4755          * to send request on I/O retry
4756          */
4757         if (wdata->mr) {
4758                 smbd_deregister_mr(wdata->mr);
4759                 wdata->mr = NULL;
4760         }
4761 #endif
4762         if (wdata->result) {
4763                 cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
4764                 trace_smb3_write_err(0 /* no xid */,
4765                                      wdata->cfile->fid.persistent_fid,
4766                                      tcon->tid, tcon->ses->Suid, wdata->offset,
4767                                      wdata->bytes, wdata->result);
4768                 if (wdata->result == -ENOSPC)
4769                         pr_warn_once("Out of space writing to %s\n",
4770                                      tcon->tree_name);
4771         } else
4772                 trace_smb3_write_done(0 /* no xid */,
4773                                       wdata->cfile->fid.persistent_fid,
4774                                       tcon->tid, tcon->ses->Suid,
4775                                       wdata->offset, wdata->bytes);
4776
4777         queue_work(cifsiod_wq, &wdata->work);
4778         release_mid(mid);
4779         add_credits(server, &credits, 0);
4780 }
4781
4782 /* smb2_async_writev - send an async write, and set up mid to handle result */
4783 int
4784 smb2_async_writev(struct cifs_writedata *wdata,
4785                   void (*release)(struct kref *kref))
4786 {
4787         int rc = -EACCES, flags = 0;
4788         struct smb2_write_req *req = NULL;
4789         struct smb2_hdr *shdr;
4790         struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
4791         struct TCP_Server_Info *server = wdata->server;
4792         struct kvec iov[1];
4793         struct smb_rqst rqst = { };
4794         unsigned int total_len;
4795         struct cifs_io_parms _io_parms;
4796         struct cifs_io_parms *io_parms = NULL;
4797         int credit_request;
4798
4799         if (!wdata->server || wdata->replay)
4800                 server = wdata->server = cifs_pick_channel(tcon->ses);
4801
4802         /*
4803          * in future we may get cifs_io_parms passed in from the caller,
4804          * but for now we construct it here...
4805          */
4806         _io_parms = (struct cifs_io_parms) {
4807                 .tcon = tcon,
4808                 .server = server,
4809                 .offset = wdata->offset,
4810                 .length = wdata->bytes,
4811                 .persistent_fid = wdata->cfile->fid.persistent_fid,
4812                 .volatile_fid = wdata->cfile->fid.volatile_fid,
4813                 .pid = wdata->pid,
4814         };
4815         io_parms = &_io_parms;
4816
4817         rc = smb2_plain_req_init(SMB2_WRITE, tcon, server,
4818                                  (void **) &req, &total_len);
4819         if (rc)
4820                 return rc;
4821
4822         if (smb3_encryption_required(tcon))
4823                 flags |= CIFS_TRANSFORM_REQ;
4824
4825         shdr = (struct smb2_hdr *)req;
4826         shdr->Id.SyncId.ProcessId = cpu_to_le32(io_parms->pid);
4827
4828         req->PersistentFileId = io_parms->persistent_fid;
4829         req->VolatileFileId = io_parms->volatile_fid;
4830         req->WriteChannelInfoOffset = 0;
4831         req->WriteChannelInfoLength = 0;
4832         req->Channel = SMB2_CHANNEL_NONE;
4833         req->Offset = cpu_to_le64(io_parms->offset);
4834         req->DataOffset = cpu_to_le16(
4835                                 offsetof(struct smb2_write_req, Buffer));
4836         req->RemainingBytes = 0;
4837
4838         trace_smb3_write_enter(0 /* xid */,
4839                                io_parms->persistent_fid,
4840                                io_parms->tcon->tid,
4841                                io_parms->tcon->ses->Suid,
4842                                io_parms->offset,
4843                                io_parms->length);
4844
4845 #ifdef CONFIG_CIFS_SMB_DIRECT
4846         /*
4847          * If we want to do a server RDMA read, fill in and append
4848          * smbd_buffer_descriptor_v1 to the end of write request
4849          */
4850         if (smb3_use_rdma_offload(io_parms)) {
4851                 struct smbd_buffer_descriptor_v1 *v1;
4852                 size_t data_size = iov_iter_count(&wdata->iter);
4853                 bool need_invalidate = server->dialect == SMB30_PROT_ID;
4854
4855                 wdata->mr = smbd_register_mr(server->smbd_conn, &wdata->iter,
4856                                              false, need_invalidate);
4857                 if (!wdata->mr) {
4858                         rc = -EAGAIN;
4859                         goto async_writev_out;
4860                 }
4861                 req->Length = 0;
4862                 req->DataOffset = 0;
4863                 req->RemainingBytes = cpu_to_le32(data_size);
4864                 req->Channel = SMB2_CHANNEL_RDMA_V1_INVALIDATE;
4865                 if (need_invalidate)
4866                         req->Channel = SMB2_CHANNEL_RDMA_V1;
4867                 req->WriteChannelInfoOffset =
4868                         cpu_to_le16(offsetof(struct smb2_write_req, Buffer));
4869                 req->WriteChannelInfoLength =
4870                         cpu_to_le16(sizeof(struct smbd_buffer_descriptor_v1));
4871                 v1 = (struct smbd_buffer_descriptor_v1 *) &req->Buffer[0];
4872                 v1->offset = cpu_to_le64(wdata->mr->mr->iova);
4873                 v1->token = cpu_to_le32(wdata->mr->mr->rkey);
4874                 v1->length = cpu_to_le32(wdata->mr->mr->length);
4875         }
4876 #endif
4877         iov[0].iov_len = total_len - 1;
4878         iov[0].iov_base = (char *)req;
4879
4880         rqst.rq_iov = iov;
4881         rqst.rq_nvec = 1;
4882         rqst.rq_iter = wdata->iter;
4883         rqst.rq_iter_size = iov_iter_count(&rqst.rq_iter);
4884         if (wdata->replay)
4885                 smb2_set_replay(server, &rqst);
4886 #ifdef CONFIG_CIFS_SMB_DIRECT
4887         if (wdata->mr)
4888                 iov[0].iov_len += sizeof(struct smbd_buffer_descriptor_v1);
4889 #endif
4890         cifs_dbg(FYI, "async write at %llu %u bytes iter=%zx\n",
4891                  io_parms->offset, io_parms->length, iov_iter_count(&rqst.rq_iter));
4892
4893 #ifdef CONFIG_CIFS_SMB_DIRECT
4894         /* For RDMA read, I/O size is in RemainingBytes not in Length */
4895         if (!wdata->mr)
4896                 req->Length = cpu_to_le32(io_parms->length);
4897 #else
4898         req->Length = cpu_to_le32(io_parms->length);
4899 #endif
4900
4901         if (wdata->credits.value > 0) {
4902                 shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(wdata->bytes,
4903                                                     SMB2_MAX_BUFFER_SIZE));
4904                 credit_request = le16_to_cpu(shdr->CreditCharge) + 8;
4905                 if (server->credits >= server->max_credits)
4906                         shdr->CreditRequest = cpu_to_le16(0);
4907                 else
4908                         shdr->CreditRequest = cpu_to_le16(
4909                                 min_t(int, server->max_credits -
4910                                                 server->credits, credit_request));
4911
4912                 rc = adjust_credits(server, &wdata->credits, io_parms->length);
4913                 if (rc)
4914                         goto async_writev_out;
4915
4916                 flags |= CIFS_HAS_CREDITS;
4917         }
4918
4919         kref_get(&wdata->refcount);
4920         rc = cifs_call_async(server, &rqst, NULL, smb2_writev_callback, NULL,
4921                              wdata, flags, &wdata->credits);
4922
4923         if (rc) {
4924                 trace_smb3_write_err(0 /* no xid */,
4925                                      io_parms->persistent_fid,
4926                                      io_parms->tcon->tid,
4927                                      io_parms->tcon->ses->Suid,
4928                                      io_parms->offset,
4929                                      io_parms->length,
4930                                      rc);
4931                 kref_put(&wdata->refcount, release);
4932                 cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
4933         }
4934
4935 async_writev_out:
4936         cifs_small_buf_release(req);
4937         return rc;
4938 }
4939
4940 /*
4941  * SMB2_write function gets iov pointer to kvec array with n_vec as a length.
4942  * The length field from io_parms must be at least 1 and indicates a number of
4943  * elements with data to write that begins with position 1 in iov array. All
4944  * data length is specified by count.
4945  */
4946 int
4947 SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms,
4948            unsigned int *nbytes, struct kvec *iov, int n_vec)
4949 {
4950         struct smb_rqst rqst;
4951         int rc = 0;
4952         struct smb2_write_req *req = NULL;
4953         struct smb2_write_rsp *rsp = NULL;
4954         int resp_buftype;
4955         struct kvec rsp_iov;
4956         int flags = 0;
4957         unsigned int total_len;
4958         struct TCP_Server_Info *server;
4959         int retries = 0, cur_sleep = 1;
4960
4961 replay_again:
4962         /* reinitialize for possible replay */
4963         flags = 0;
4964         *nbytes = 0;
4965         if (!io_parms->server)
4966                 io_parms->server = cifs_pick_channel(io_parms->tcon->ses);
4967         server = io_parms->server;
4968         if (server == NULL)
4969                 return -ECONNABORTED;
4970
4971         if (n_vec < 1)
4972                 return rc;
4973
4974         rc = smb2_plain_req_init(SMB2_WRITE, io_parms->tcon, server,
4975                                  (void **) &req, &total_len);
4976         if (rc)
4977                 return rc;
4978
4979         if (smb3_encryption_required(io_parms->tcon))
4980                 flags |= CIFS_TRANSFORM_REQ;
4981
4982         req->hdr.Id.SyncId.ProcessId = cpu_to_le32(io_parms->pid);
4983
4984         req->PersistentFileId = io_parms->persistent_fid;
4985         req->VolatileFileId = io_parms->volatile_fid;
4986         req->WriteChannelInfoOffset = 0;
4987         req->WriteChannelInfoLength = 0;
4988         req->Channel = 0;
4989         req->Length = cpu_to_le32(io_parms->length);
4990         req->Offset = cpu_to_le64(io_parms->offset);
4991         req->DataOffset = cpu_to_le16(
4992                                 offsetof(struct smb2_write_req, Buffer));
4993         req->RemainingBytes = 0;
4994
4995         trace_smb3_write_enter(xid, io_parms->persistent_fid,
4996                 io_parms->tcon->tid, io_parms->tcon->ses->Suid,
4997                 io_parms->offset, io_parms->length);
4998
4999         iov[0].iov_base = (char *)req;
5000         /* 1 for Buffer */
5001         iov[0].iov_len = total_len - 1;
5002
5003         memset(&rqst, 0, sizeof(struct smb_rqst));
5004         rqst.rq_iov = iov;
5005         rqst.rq_nvec = n_vec + 1;
5006
5007         if (retries)
5008                 smb2_set_replay(server, &rqst);
5009
5010         rc = cifs_send_recv(xid, io_parms->tcon->ses, server,
5011                             &rqst,
5012                             &resp_buftype, flags, &rsp_iov);
5013         rsp = (struct smb2_write_rsp *)rsp_iov.iov_base;
5014
5015         if (rc) {
5016                 trace_smb3_write_err(xid,
5017                                      req->PersistentFileId,
5018                                      io_parms->tcon->tid,
5019                                      io_parms->tcon->ses->Suid,
5020                                      io_parms->offset, io_parms->length, rc);
5021                 cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE);
5022                 cifs_dbg(VFS, "Send error in write = %d\n", rc);
5023         } else {
5024                 *nbytes = le32_to_cpu(rsp->DataLength);
5025                 trace_smb3_write_done(xid,
5026                                       req->PersistentFileId,
5027                                       io_parms->tcon->tid,
5028                                       io_parms->tcon->ses->Suid,
5029                                       io_parms->offset, *nbytes);
5030         }
5031
5032         cifs_small_buf_release(req);
5033         free_rsp_buf(resp_buftype, rsp);
5034
5035         if (is_replayable_error(rc) &&
5036             smb2_should_replay(io_parms->tcon, &retries, &cur_sleep))
5037                 goto replay_again;
5038
5039         return rc;
5040 }
5041
5042 int posix_info_sid_size(const void *beg, const void *end)
5043 {
5044         size_t subauth;
5045         int total;
5046
5047         if (beg + 1 > end)
5048                 return -1;
5049
5050         subauth = *(u8 *)(beg+1);
5051         if (subauth < 1 || subauth > 15)
5052                 return -1;
5053
5054         total = 1 + 1 + 6 + 4*subauth;
5055         if (beg + total > end)
5056                 return -1;
5057
5058         return total;
5059 }
5060
5061 int posix_info_parse(const void *beg, const void *end,
5062                      struct smb2_posix_info_parsed *out)
5063
5064 {
5065         int total_len = 0;
5066         int owner_len, group_len;
5067         int name_len;
5068         const void *owner_sid;
5069         const void *group_sid;
5070         const void *name;
5071
5072         /* if no end bound given, assume payload to be correct */
5073         if (!end) {
5074                 const struct smb2_posix_info *p = beg;
5075
5076                 end = beg + le32_to_cpu(p->NextEntryOffset);
5077                 /* last element will have a 0 offset, pick a sensible bound */
5078                 if (end == beg)
5079                         end += 0xFFFF;
5080         }
5081
5082         /* check base buf */
5083         if (beg + sizeof(struct smb2_posix_info) > end)
5084                 return -1;
5085         total_len = sizeof(struct smb2_posix_info);
5086
5087         /* check owner sid */
5088         owner_sid = beg + total_len;
5089         owner_len = posix_info_sid_size(owner_sid, end);
5090         if (owner_len < 0)
5091                 return -1;
5092         total_len += owner_len;
5093
5094         /* check group sid */
5095         group_sid = beg + total_len;
5096         group_len = posix_info_sid_size(group_sid, end);
5097         if (group_len < 0)
5098                 return -1;
5099         total_len += group_len;
5100
5101         /* check name len */
5102         if (beg + total_len + 4 > end)
5103                 return -1;
5104         name_len = le32_to_cpu(*(__le32 *)(beg + total_len));
5105         if (name_len < 1 || name_len > 0xFFFF)
5106                 return -1;
5107         total_len += 4;
5108
5109         /* check name */
5110         name = beg + total_len;
5111         if (name + name_len > end)
5112                 return -1;
5113         total_len += name_len;
5114
5115         if (out) {
5116                 out->base = beg;
5117                 out->size = total_len;
5118                 out->name_len = name_len;
5119                 out->name = name;
5120                 memcpy(&out->owner, owner_sid, owner_len);
5121                 memcpy(&out->group, group_sid, group_len);
5122         }
5123         return total_len;
5124 }
5125
5126 static int posix_info_extra_size(const void *beg, const void *end)
5127 {
5128         int len = posix_info_parse(beg, end, NULL);
5129
5130         if (len < 0)
5131                 return -1;
5132         return len - sizeof(struct smb2_posix_info);
5133 }
5134
5135 static unsigned int
5136 num_entries(int infotype, char *bufstart, char *end_of_buf, char **lastentry,
5137             size_t size)
5138 {
5139         int len;
5140         unsigned int entrycount = 0;
5141         unsigned int next_offset = 0;
5142         char *entryptr;
5143         FILE_DIRECTORY_INFO *dir_info;
5144
5145         if (bufstart == NULL)
5146                 return 0;
5147
5148         entryptr = bufstart;
5149
5150         while (1) {
5151                 if (entryptr + next_offset < entryptr ||
5152                     entryptr + next_offset > end_of_buf ||
5153                     entryptr + next_offset + size > end_of_buf) {
5154                         cifs_dbg(VFS, "malformed search entry would overflow\n");
5155                         break;
5156                 }
5157
5158                 entryptr = entryptr + next_offset;
5159                 dir_info = (FILE_DIRECTORY_INFO *)entryptr;
5160
5161                 if (infotype == SMB_FIND_FILE_POSIX_INFO)
5162                         len = posix_info_extra_size(entryptr, end_of_buf);
5163                 else
5164                         len = le32_to_cpu(dir_info->FileNameLength);
5165
5166                 if (len < 0 ||
5167                     entryptr + len < entryptr ||
5168                     entryptr + len > end_of_buf ||
5169                     entryptr + len + size > end_of_buf) {
5170                         cifs_dbg(VFS, "directory entry name would overflow frame end of buf %p\n",
5171                                  end_of_buf);
5172                         break;
5173                 }
5174
5175                 *lastentry = entryptr;
5176                 entrycount++;
5177
5178                 next_offset = le32_to_cpu(dir_info->NextEntryOffset);
5179                 if (!next_offset)
5180                         break;
5181         }
5182
5183         return entrycount;
5184 }
5185
5186 /*
5187  * Readdir/FindFirst
5188  */
5189 int SMB2_query_directory_init(const unsigned int xid,
5190                               struct cifs_tcon *tcon,
5191                               struct TCP_Server_Info *server,
5192                               struct smb_rqst *rqst,
5193                               u64 persistent_fid, u64 volatile_fid,
5194                               int index, int info_level)
5195 {
5196         struct smb2_query_directory_req *req;
5197         unsigned char *bufptr;
5198         __le16 asteriks = cpu_to_le16('*');
5199         unsigned int output_size = CIFSMaxBufSize -
5200                 MAX_SMB2_CREATE_RESPONSE_SIZE -
5201                 MAX_SMB2_CLOSE_RESPONSE_SIZE;
5202         unsigned int total_len;
5203         struct kvec *iov = rqst->rq_iov;
5204         int len, rc;
5205
5206         rc = smb2_plain_req_init(SMB2_QUERY_DIRECTORY, tcon, server,
5207                                  (void **) &req, &total_len);
5208         if (rc)
5209                 return rc;
5210
5211         switch (info_level) {
5212         case SMB_FIND_FILE_DIRECTORY_INFO:
5213                 req->FileInformationClass = FILE_DIRECTORY_INFORMATION;
5214                 break;
5215         case SMB_FIND_FILE_ID_FULL_DIR_INFO:
5216                 req->FileInformationClass = FILEID_FULL_DIRECTORY_INFORMATION;
5217                 break;
5218         case SMB_FIND_FILE_POSIX_INFO:
5219                 req->FileInformationClass = SMB_FIND_FILE_POSIX_INFO;
5220                 break;
5221         case SMB_FIND_FILE_FULL_DIRECTORY_INFO:
5222                 req->FileInformationClass = FILE_FULL_DIRECTORY_INFORMATION;
5223                 break;
5224         default:
5225                 cifs_tcon_dbg(VFS, "info level %u isn't supported\n",
5226                         info_level);
5227                 return -EINVAL;
5228         }
5229
5230         req->FileIndex = cpu_to_le32(index);
5231         req->PersistentFileId = persistent_fid;
5232         req->VolatileFileId = volatile_fid;
5233
5234         len = 0x2;
5235         bufptr = req->Buffer;
5236         memcpy(bufptr, &asteriks, len);
5237
5238         req->FileNameOffset =
5239                 cpu_to_le16(sizeof(struct smb2_query_directory_req));
5240         req->FileNameLength = cpu_to_le16(len);
5241         /*
5242          * BB could be 30 bytes or so longer if we used SMB2 specific
5243          * buffer lengths, but this is safe and close enough.
5244          */
5245         output_size = min_t(unsigned int, output_size, server->maxBuf);
5246         output_size = min_t(unsigned int, output_size, 2 << 15);
5247         req->OutputBufferLength = cpu_to_le32(output_size);
5248
5249         iov[0].iov_base = (char *)req;
5250         /* 1 for Buffer */
5251         iov[0].iov_len = total_len - 1;
5252
5253         iov[1].iov_base = (char *)(req->Buffer);
5254         iov[1].iov_len = len;
5255
5256         trace_smb3_query_dir_enter(xid, persistent_fid, tcon->tid,
5257                         tcon->ses->Suid, index, output_size);
5258
5259         return 0;
5260 }
5261
5262 void SMB2_query_directory_free(struct smb_rqst *rqst)
5263 {
5264         if (rqst && rqst->rq_iov) {
5265                 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
5266         }
5267 }
5268
5269 int
5270 smb2_parse_query_directory(struct cifs_tcon *tcon,
5271                            struct kvec *rsp_iov,
5272                            int resp_buftype,
5273                            struct cifs_search_info *srch_inf)
5274 {
5275         struct smb2_query_directory_rsp *rsp;
5276         size_t info_buf_size;
5277         char *end_of_smb;
5278         int rc;
5279
5280         rsp = (struct smb2_query_directory_rsp *)rsp_iov->iov_base;
5281
5282         switch (srch_inf->info_level) {
5283         case SMB_FIND_FILE_DIRECTORY_INFO:
5284                 info_buf_size = sizeof(FILE_DIRECTORY_INFO);
5285                 break;
5286         case SMB_FIND_FILE_ID_FULL_DIR_INFO:
5287                 info_buf_size = sizeof(SEARCH_ID_FULL_DIR_INFO);
5288                 break;
5289         case SMB_FIND_FILE_POSIX_INFO:
5290                 /* note that posix payload are variable size */
5291                 info_buf_size = sizeof(struct smb2_posix_info);
5292                 break;
5293         case SMB_FIND_FILE_FULL_DIRECTORY_INFO:
5294                 info_buf_size = sizeof(FILE_FULL_DIRECTORY_INFO);
5295                 break;
5296         default:
5297                 cifs_tcon_dbg(VFS, "info level %u isn't supported\n",
5298                          srch_inf->info_level);
5299                 return -EINVAL;
5300         }
5301
5302         rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
5303                                le32_to_cpu(rsp->OutputBufferLength), rsp_iov,
5304                                info_buf_size);
5305         if (rc) {
5306                 cifs_tcon_dbg(VFS, "bad info payload");
5307                 return rc;
5308         }
5309
5310         srch_inf->unicode = true;
5311
5312         if (srch_inf->ntwrk_buf_start) {
5313                 if (srch_inf->smallBuf)
5314                         cifs_small_buf_release(srch_inf->ntwrk_buf_start);
5315                 else
5316                         cifs_buf_release(srch_inf->ntwrk_buf_start);
5317         }
5318         srch_inf->ntwrk_buf_start = (char *)rsp;
5319         srch_inf->srch_entries_start = srch_inf->last_entry =
5320                 (char *)rsp + le16_to_cpu(rsp->OutputBufferOffset);
5321         end_of_smb = rsp_iov->iov_len + (char *)rsp;
5322
5323         srch_inf->entries_in_buffer = num_entries(
5324                 srch_inf->info_level,
5325                 srch_inf->srch_entries_start,
5326                 end_of_smb,
5327                 &srch_inf->last_entry,
5328                 info_buf_size);
5329
5330         srch_inf->index_of_last_entry += srch_inf->entries_in_buffer;
5331         cifs_dbg(FYI, "num entries %d last_index %lld srch start %p srch end %p\n",
5332                  srch_inf->entries_in_buffer, srch_inf->index_of_last_entry,
5333                  srch_inf->srch_entries_start, srch_inf->last_entry);
5334         if (resp_buftype == CIFS_LARGE_BUFFER)
5335                 srch_inf->smallBuf = false;
5336         else if (resp_buftype == CIFS_SMALL_BUFFER)
5337                 srch_inf->smallBuf = true;
5338         else
5339                 cifs_tcon_dbg(VFS, "Invalid search buffer type\n");
5340
5341         return 0;
5342 }
5343
5344 int
5345 SMB2_query_directory(const unsigned int xid, struct cifs_tcon *tcon,
5346                      u64 persistent_fid, u64 volatile_fid, int index,
5347                      struct cifs_search_info *srch_inf)
5348 {
5349         struct smb_rqst rqst;
5350         struct kvec iov[SMB2_QUERY_DIRECTORY_IOV_SIZE];
5351         struct smb2_query_directory_rsp *rsp = NULL;
5352         int resp_buftype = CIFS_NO_BUFFER;
5353         struct kvec rsp_iov;
5354         int rc = 0;
5355         struct cifs_ses *ses = tcon->ses;
5356         struct TCP_Server_Info *server;
5357         int flags = 0;
5358         int retries = 0, cur_sleep = 1;
5359
5360 replay_again:
5361         /* reinitialize for possible replay */
5362         flags = 0;
5363         server = cifs_pick_channel(ses);
5364
5365         if (!ses || !(ses->server))
5366                 return -EIO;
5367
5368         if (smb3_encryption_required(tcon))
5369                 flags |= CIFS_TRANSFORM_REQ;
5370
5371         memset(&rqst, 0, sizeof(struct smb_rqst));
5372         memset(&iov, 0, sizeof(iov));
5373         rqst.rq_iov = iov;
5374         rqst.rq_nvec = SMB2_QUERY_DIRECTORY_IOV_SIZE;
5375
5376         rc = SMB2_query_directory_init(xid, tcon, server,
5377                                        &rqst, persistent_fid,
5378                                        volatile_fid, index,
5379                                        srch_inf->info_level);
5380         if (rc)
5381                 goto qdir_exit;
5382
5383         if (retries)
5384                 smb2_set_replay(server, &rqst);
5385
5386         rc = cifs_send_recv(xid, ses, server,
5387                             &rqst, &resp_buftype, flags, &rsp_iov);
5388         rsp = (struct smb2_query_directory_rsp *)rsp_iov.iov_base;
5389
5390         if (rc) {
5391                 if (rc == -ENODATA &&
5392                     rsp->hdr.Status == STATUS_NO_MORE_FILES) {
5393                         trace_smb3_query_dir_done(xid, persistent_fid,
5394                                 tcon->tid, tcon->ses->Suid, index, 0);
5395                         srch_inf->endOfSearch = true;
5396                         rc = 0;
5397                 } else {
5398                         trace_smb3_query_dir_err(xid, persistent_fid, tcon->tid,
5399                                 tcon->ses->Suid, index, 0, rc);
5400                         cifs_stats_fail_inc(tcon, SMB2_QUERY_DIRECTORY_HE);
5401                 }
5402                 goto qdir_exit;
5403         }
5404
5405         rc = smb2_parse_query_directory(tcon, &rsp_iov, resp_buftype,
5406                                         srch_inf);
5407         if (rc) {
5408                 trace_smb3_query_dir_err(xid, persistent_fid, tcon->tid,
5409                         tcon->ses->Suid, index, 0, rc);
5410                 goto qdir_exit;
5411         }
5412         resp_buftype = CIFS_NO_BUFFER;
5413
5414         trace_smb3_query_dir_done(xid, persistent_fid, tcon->tid,
5415                         tcon->ses->Suid, index, srch_inf->entries_in_buffer);
5416
5417 qdir_exit:
5418         SMB2_query_directory_free(&rqst);
5419         free_rsp_buf(resp_buftype, rsp);
5420
5421         if (is_replayable_error(rc) &&
5422             smb2_should_replay(tcon, &retries, &cur_sleep))
5423                 goto replay_again;
5424
5425         return rc;
5426 }
5427
5428 int
5429 SMB2_set_info_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
5430                    struct smb_rqst *rqst,
5431                    u64 persistent_fid, u64 volatile_fid, u32 pid,
5432                    u8 info_class, u8 info_type, u32 additional_info,
5433                    void **data, unsigned int *size)
5434 {
5435         struct smb2_set_info_req *req;
5436         struct kvec *iov = rqst->rq_iov;
5437         unsigned int i, total_len;
5438         int rc;
5439
5440         rc = smb2_plain_req_init(SMB2_SET_INFO, tcon, server,
5441                                  (void **) &req, &total_len);
5442         if (rc)
5443                 return rc;
5444
5445         req->hdr.Id.SyncId.ProcessId = cpu_to_le32(pid);
5446         req->InfoType = info_type;
5447         req->FileInfoClass = info_class;
5448         req->PersistentFileId = persistent_fid;
5449         req->VolatileFileId = volatile_fid;
5450         req->AdditionalInformation = cpu_to_le32(additional_info);
5451
5452         req->BufferOffset = cpu_to_le16(sizeof(struct smb2_set_info_req));
5453         req->BufferLength = cpu_to_le32(*size);
5454
5455         memcpy(req->Buffer, *data, *size);
5456         total_len += *size;
5457
5458         iov[0].iov_base = (char *)req;
5459         /* 1 for Buffer */
5460         iov[0].iov_len = total_len - 1;
5461
5462         for (i = 1; i < rqst->rq_nvec; i++) {
5463                 le32_add_cpu(&req->BufferLength, size[i]);
5464                 iov[i].iov_base = (char *)data[i];
5465                 iov[i].iov_len = size[i];
5466         }
5467
5468         return 0;
5469 }
5470
5471 void
5472 SMB2_set_info_free(struct smb_rqst *rqst)
5473 {
5474         if (rqst && rqst->rq_iov)
5475                 cifs_buf_release(rqst->rq_iov[0].iov_base); /* request */
5476 }
5477
5478 static int
5479 send_set_info(const unsigned int xid, struct cifs_tcon *tcon,
5480                u64 persistent_fid, u64 volatile_fid, u32 pid, u8 info_class,
5481                u8 info_type, u32 additional_info, unsigned int num,
5482                 void **data, unsigned int *size)
5483 {
5484         struct smb_rqst rqst;
5485         struct smb2_set_info_rsp *rsp = NULL;
5486         struct kvec *iov;
5487         struct kvec rsp_iov;
5488         int rc = 0;
5489         int resp_buftype;
5490         struct cifs_ses *ses = tcon->ses;
5491         struct TCP_Server_Info *server;
5492         int flags = 0;
5493         int retries = 0, cur_sleep = 1;
5494
5495 replay_again:
5496         /* reinitialize for possible replay */
5497         flags = 0;
5498         server = cifs_pick_channel(ses);
5499
5500         if (!ses || !server)
5501                 return -EIO;
5502
5503         if (!num)
5504                 return -EINVAL;
5505
5506         if (smb3_encryption_required(tcon))
5507                 flags |= CIFS_TRANSFORM_REQ;
5508
5509         iov = kmalloc_array(num, sizeof(struct kvec), GFP_KERNEL);
5510         if (!iov)
5511                 return -ENOMEM;
5512
5513         memset(&rqst, 0, sizeof(struct smb_rqst));
5514         rqst.rq_iov = iov;
5515         rqst.rq_nvec = num;
5516
5517         rc = SMB2_set_info_init(tcon, server,
5518                                 &rqst, persistent_fid, volatile_fid, pid,
5519                                 info_class, info_type, additional_info,
5520                                 data, size);
5521         if (rc) {
5522                 kfree(iov);
5523                 return rc;
5524         }
5525
5526         if (retries)
5527                 smb2_set_replay(server, &rqst);
5528
5529         rc = cifs_send_recv(xid, ses, server,
5530                             &rqst, &resp_buftype, flags,
5531                             &rsp_iov);
5532         SMB2_set_info_free(&rqst);
5533         rsp = (struct smb2_set_info_rsp *)rsp_iov.iov_base;
5534
5535         if (rc != 0) {
5536                 cifs_stats_fail_inc(tcon, SMB2_SET_INFO_HE);
5537                 trace_smb3_set_info_err(xid, persistent_fid, tcon->tid,
5538                                 ses->Suid, info_class, (__u32)info_type, rc);
5539         }
5540
5541         free_rsp_buf(resp_buftype, rsp);
5542         kfree(iov);
5543
5544         if (is_replayable_error(rc) &&
5545             smb2_should_replay(tcon, &retries, &cur_sleep))
5546                 goto replay_again;
5547
5548         return rc;
5549 }
5550
5551 int
5552 SMB2_set_eof(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
5553              u64 volatile_fid, u32 pid, loff_t new_eof)
5554 {
5555         struct smb2_file_eof_info info;
5556         void *data;
5557         unsigned int size;
5558
5559         info.EndOfFile = cpu_to_le64(new_eof);
5560
5561         data = &info;
5562         size = sizeof(struct smb2_file_eof_info);
5563
5564         trace_smb3_set_eof(xid, persistent_fid, tcon->tid, tcon->ses->Suid, new_eof);
5565
5566         return send_set_info(xid, tcon, persistent_fid, volatile_fid,
5567                         pid, FILE_END_OF_FILE_INFORMATION, SMB2_O_INFO_FILE,
5568                         0, 1, &data, &size);
5569 }
5570
5571 int
5572 SMB2_set_acl(const unsigned int xid, struct cifs_tcon *tcon,
5573                 u64 persistent_fid, u64 volatile_fid,
5574                 struct cifs_ntsd *pnntsd, int pacllen, int aclflag)
5575 {
5576         return send_set_info(xid, tcon, persistent_fid, volatile_fid,
5577                         current->tgid, 0, SMB2_O_INFO_SECURITY, aclflag,
5578                         1, (void **)&pnntsd, &pacllen);
5579 }
5580
5581 int
5582 SMB2_set_ea(const unsigned int xid, struct cifs_tcon *tcon,
5583             u64 persistent_fid, u64 volatile_fid,
5584             struct smb2_file_full_ea_info *buf, int len)
5585 {
5586         return send_set_info(xid, tcon, persistent_fid, volatile_fid,
5587                 current->tgid, FILE_FULL_EA_INFORMATION, SMB2_O_INFO_FILE,
5588                 0, 1, (void **)&buf, &len);
5589 }
5590
5591 int
5592 SMB2_oplock_break(const unsigned int xid, struct cifs_tcon *tcon,
5593                   const u64 persistent_fid, const u64 volatile_fid,
5594                   __u8 oplock_level)
5595 {
5596         struct smb_rqst rqst;
5597         int rc;
5598         struct smb2_oplock_break *req = NULL;
5599         struct cifs_ses *ses = tcon->ses;
5600         struct TCP_Server_Info *server;
5601         int flags = CIFS_OBREAK_OP;
5602         unsigned int total_len;
5603         struct kvec iov[1];
5604         struct kvec rsp_iov;
5605         int resp_buf_type;
5606         int retries = 0, cur_sleep = 1;
5607
5608 replay_again:
5609         /* reinitialize for possible replay */
5610         flags = CIFS_OBREAK_OP;
5611         server = cifs_pick_channel(ses);
5612
5613         cifs_dbg(FYI, "SMB2_oplock_break\n");
5614         rc = smb2_plain_req_init(SMB2_OPLOCK_BREAK, tcon, server,
5615                                  (void **) &req, &total_len);
5616         if (rc)
5617                 return rc;
5618
5619         if (smb3_encryption_required(tcon))
5620                 flags |= CIFS_TRANSFORM_REQ;
5621
5622         req->VolatileFid = volatile_fid;
5623         req->PersistentFid = persistent_fid;
5624         req->OplockLevel = oplock_level;
5625         req->hdr.CreditRequest = cpu_to_le16(1);
5626
5627         flags |= CIFS_NO_RSP_BUF;
5628
5629         iov[0].iov_base = (char *)req;
5630         iov[0].iov_len = total_len;
5631
5632         memset(&rqst, 0, sizeof(struct smb_rqst));
5633         rqst.rq_iov = iov;
5634         rqst.rq_nvec = 1;
5635
5636         if (retries)
5637                 smb2_set_replay(server, &rqst);
5638
5639         rc = cifs_send_recv(xid, ses, server,
5640                             &rqst, &resp_buf_type, flags, &rsp_iov);
5641         cifs_small_buf_release(req);
5642         if (rc) {
5643                 cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
5644                 cifs_dbg(FYI, "Send error in Oplock Break = %d\n", rc);
5645         }
5646
5647         if (is_replayable_error(rc) &&
5648             smb2_should_replay(tcon, &retries, &cur_sleep))
5649                 goto replay_again;
5650
5651         return rc;
5652 }
5653
5654 void
5655 smb2_copy_fs_info_to_kstatfs(struct smb2_fs_full_size_info *pfs_inf,
5656                              struct kstatfs *kst)
5657 {
5658         kst->f_bsize = le32_to_cpu(pfs_inf->BytesPerSector) *
5659                           le32_to_cpu(pfs_inf->SectorsPerAllocationUnit);
5660         kst->f_blocks = le64_to_cpu(pfs_inf->TotalAllocationUnits);
5661         kst->f_bfree  = kst->f_bavail =
5662                         le64_to_cpu(pfs_inf->CallerAvailableAllocationUnits);
5663         return;
5664 }
5665
5666 static void
5667 copy_posix_fs_info_to_kstatfs(FILE_SYSTEM_POSIX_INFO *response_data,
5668                         struct kstatfs *kst)
5669 {
5670         kst->f_bsize = le32_to_cpu(response_data->BlockSize);
5671         kst->f_blocks = le64_to_cpu(response_data->TotalBlocks);
5672         kst->f_bfree =  le64_to_cpu(response_data->BlocksAvail);
5673         if (response_data->UserBlocksAvail == cpu_to_le64(-1))
5674                 kst->f_bavail = kst->f_bfree;
5675         else
5676                 kst->f_bavail = le64_to_cpu(response_data->UserBlocksAvail);
5677         if (response_data->TotalFileNodes != cpu_to_le64(-1))
5678                 kst->f_files = le64_to_cpu(response_data->TotalFileNodes);
5679         if (response_data->FreeFileNodes != cpu_to_le64(-1))
5680                 kst->f_ffree = le64_to_cpu(response_data->FreeFileNodes);
5681
5682         return;
5683 }
5684
5685 static int
5686 build_qfs_info_req(struct kvec *iov, struct cifs_tcon *tcon,
5687                    struct TCP_Server_Info *server,
5688                    int level, int outbuf_len, u64 persistent_fid,
5689                    u64 volatile_fid)
5690 {
5691         int rc;
5692         struct smb2_query_info_req *req;
5693         unsigned int total_len;
5694
5695         cifs_dbg(FYI, "Query FSInfo level %d\n", level);
5696
5697         if ((tcon->ses == NULL) || server == NULL)
5698                 return -EIO;
5699
5700         rc = smb2_plain_req_init(SMB2_QUERY_INFO, tcon, server,
5701                                  (void **) &req, &total_len);
5702         if (rc)
5703                 return rc;
5704
5705         req->InfoType = SMB2_O_INFO_FILESYSTEM;
5706         req->FileInfoClass = level;
5707         req->PersistentFileId = persistent_fid;
5708         req->VolatileFileId = volatile_fid;
5709         /* 1 for pad */
5710         req->InputBufferOffset =
5711                         cpu_to_le16(sizeof(struct smb2_query_info_req));
5712         req->OutputBufferLength = cpu_to_le32(
5713                 outbuf_len + sizeof(struct smb2_query_info_rsp));
5714
5715         iov->iov_base = (char *)req;
5716         iov->iov_len = total_len;
5717         return 0;
5718 }
5719
5720 static inline void free_qfs_info_req(struct kvec *iov)
5721 {
5722         cifs_buf_release(iov->iov_base);
5723 }
5724
5725 int
5726 SMB311_posix_qfs_info(const unsigned int xid, struct cifs_tcon *tcon,
5727               u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata)
5728 {
5729         struct smb_rqst rqst;
5730         struct smb2_query_info_rsp *rsp = NULL;
5731         struct kvec iov;
5732         struct kvec rsp_iov;
5733         int rc = 0;
5734         int resp_buftype;
5735         struct cifs_ses *ses = tcon->ses;
5736         struct TCP_Server_Info *server;
5737         FILE_SYSTEM_POSIX_INFO *info = NULL;
5738         int flags = 0;
5739         int retries = 0, cur_sleep = 1;
5740
5741 replay_again:
5742         /* reinitialize for possible replay */
5743         flags = 0;
5744         server = cifs_pick_channel(ses);
5745
5746         rc = build_qfs_info_req(&iov, tcon, server,
5747                                 FS_POSIX_INFORMATION,
5748                                 sizeof(FILE_SYSTEM_POSIX_INFO),
5749                                 persistent_fid, volatile_fid);
5750         if (rc)
5751                 return rc;
5752
5753         if (smb3_encryption_required(tcon))
5754                 flags |= CIFS_TRANSFORM_REQ;
5755
5756         memset(&rqst, 0, sizeof(struct smb_rqst));
5757         rqst.rq_iov = &iov;
5758         rqst.rq_nvec = 1;
5759
5760         if (retries)
5761                 smb2_set_replay(server, &rqst);
5762
5763         rc = cifs_send_recv(xid, ses, server,
5764                             &rqst, &resp_buftype, flags, &rsp_iov);
5765         free_qfs_info_req(&iov);
5766         if (rc) {
5767                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
5768                 goto posix_qfsinf_exit;
5769         }
5770         rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
5771
5772         info = (FILE_SYSTEM_POSIX_INFO *)(
5773                 le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp);
5774         rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
5775                                le32_to_cpu(rsp->OutputBufferLength), &rsp_iov,
5776                                sizeof(FILE_SYSTEM_POSIX_INFO));
5777         if (!rc)
5778                 copy_posix_fs_info_to_kstatfs(info, fsdata);
5779
5780 posix_qfsinf_exit:
5781         free_rsp_buf(resp_buftype, rsp_iov.iov_base);
5782
5783         if (is_replayable_error(rc) &&
5784             smb2_should_replay(tcon, &retries, &cur_sleep))
5785                 goto replay_again;
5786
5787         return rc;
5788 }
5789
5790 int
5791 SMB2_QFS_info(const unsigned int xid, struct cifs_tcon *tcon,
5792               u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata)
5793 {
5794         struct smb_rqst rqst;
5795         struct smb2_query_info_rsp *rsp = NULL;
5796         struct kvec iov;
5797         struct kvec rsp_iov;
5798         int rc = 0;
5799         int resp_buftype;
5800         struct cifs_ses *ses = tcon->ses;
5801         struct TCP_Server_Info *server;
5802         struct smb2_fs_full_size_info *info = NULL;
5803         int flags = 0;
5804         int retries = 0, cur_sleep = 1;
5805
5806 replay_again:
5807         /* reinitialize for possible replay */
5808         flags = 0;
5809         server = cifs_pick_channel(ses);
5810
5811         rc = build_qfs_info_req(&iov, tcon, server,
5812                                 FS_FULL_SIZE_INFORMATION,
5813                                 sizeof(struct smb2_fs_full_size_info),
5814                                 persistent_fid, volatile_fid);
5815         if (rc)
5816                 return rc;
5817
5818         if (smb3_encryption_required(tcon))
5819                 flags |= CIFS_TRANSFORM_REQ;
5820
5821         memset(&rqst, 0, sizeof(struct smb_rqst));
5822         rqst.rq_iov = &iov;
5823         rqst.rq_nvec = 1;
5824
5825         if (retries)
5826                 smb2_set_replay(server, &rqst);
5827
5828         rc = cifs_send_recv(xid, ses, server,
5829                             &rqst, &resp_buftype, flags, &rsp_iov);
5830         free_qfs_info_req(&iov);
5831         if (rc) {
5832                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
5833                 goto qfsinf_exit;
5834         }
5835         rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
5836
5837         info = (struct smb2_fs_full_size_info *)(
5838                 le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp);
5839         rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
5840                                le32_to_cpu(rsp->OutputBufferLength), &rsp_iov,
5841                                sizeof(struct smb2_fs_full_size_info));
5842         if (!rc)
5843                 smb2_copy_fs_info_to_kstatfs(info, fsdata);
5844
5845 qfsinf_exit:
5846         free_rsp_buf(resp_buftype, rsp_iov.iov_base);
5847
5848         if (is_replayable_error(rc) &&
5849             smb2_should_replay(tcon, &retries, &cur_sleep))
5850                 goto replay_again;
5851
5852         return rc;
5853 }
5854
5855 int
5856 SMB2_QFS_attr(const unsigned int xid, struct cifs_tcon *tcon,
5857               u64 persistent_fid, u64 volatile_fid, int level)
5858 {
5859         struct smb_rqst rqst;
5860         struct smb2_query_info_rsp *rsp = NULL;
5861         struct kvec iov;
5862         struct kvec rsp_iov;
5863         int rc = 0;
5864         int resp_buftype, max_len, min_len;
5865         struct cifs_ses *ses = tcon->ses;
5866         struct TCP_Server_Info *server;
5867         unsigned int rsp_len, offset;
5868         int flags = 0;
5869         int retries = 0, cur_sleep = 1;
5870
5871 replay_again:
5872         /* reinitialize for possible replay */
5873         flags = 0;
5874         server = cifs_pick_channel(ses);
5875
5876         if (level == FS_DEVICE_INFORMATION) {
5877                 max_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
5878                 min_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
5879         } else if (level == FS_ATTRIBUTE_INFORMATION) {
5880                 max_len = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO);
5881                 min_len = MIN_FS_ATTR_INFO_SIZE;
5882         } else if (level == FS_SECTOR_SIZE_INFORMATION) {
5883                 max_len = sizeof(struct smb3_fs_ss_info);
5884                 min_len = sizeof(struct smb3_fs_ss_info);
5885         } else if (level == FS_VOLUME_INFORMATION) {
5886                 max_len = sizeof(struct smb3_fs_vol_info) + MAX_VOL_LABEL_LEN;
5887                 min_len = sizeof(struct smb3_fs_vol_info);
5888         } else {
5889                 cifs_dbg(FYI, "Invalid qfsinfo level %d\n", level);
5890                 return -EINVAL;
5891         }
5892
5893         rc = build_qfs_info_req(&iov, tcon, server,
5894                                 level, max_len,
5895                                 persistent_fid, volatile_fid);
5896         if (rc)
5897                 return rc;
5898
5899         if (smb3_encryption_required(tcon))
5900                 flags |= CIFS_TRANSFORM_REQ;
5901
5902         memset(&rqst, 0, sizeof(struct smb_rqst));
5903         rqst.rq_iov = &iov;
5904         rqst.rq_nvec = 1;
5905
5906         if (retries)
5907                 smb2_set_replay(server, &rqst);
5908
5909         rc = cifs_send_recv(xid, ses, server,
5910                             &rqst, &resp_buftype, flags, &rsp_iov);
5911         free_qfs_info_req(&iov);
5912         if (rc) {
5913                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
5914                 goto qfsattr_exit;
5915         }
5916         rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
5917
5918         rsp_len = le32_to_cpu(rsp->OutputBufferLength);
5919         offset = le16_to_cpu(rsp->OutputBufferOffset);
5920         rc = smb2_validate_iov(offset, rsp_len, &rsp_iov, min_len);
5921         if (rc)
5922                 goto qfsattr_exit;
5923
5924         if (level == FS_ATTRIBUTE_INFORMATION)
5925                 memcpy(&tcon->fsAttrInfo, offset
5926                         + (char *)rsp, min_t(unsigned int,
5927                         rsp_len, max_len));
5928         else if (level == FS_DEVICE_INFORMATION)
5929                 memcpy(&tcon->fsDevInfo, offset
5930                         + (char *)rsp, sizeof(FILE_SYSTEM_DEVICE_INFO));
5931         else if (level == FS_SECTOR_SIZE_INFORMATION) {
5932                 struct smb3_fs_ss_info *ss_info = (struct smb3_fs_ss_info *)
5933                         (offset + (char *)rsp);
5934                 tcon->ss_flags = le32_to_cpu(ss_info->Flags);
5935                 tcon->perf_sector_size =
5936                         le32_to_cpu(ss_info->PhysicalBytesPerSectorForPerf);
5937         } else if (level == FS_VOLUME_INFORMATION) {
5938                 struct smb3_fs_vol_info *vol_info = (struct smb3_fs_vol_info *)
5939                         (offset + (char *)rsp);
5940                 tcon->vol_serial_number = vol_info->VolumeSerialNumber;
5941                 tcon->vol_create_time = vol_info->VolumeCreationTime;
5942         }
5943
5944 qfsattr_exit:
5945         free_rsp_buf(resp_buftype, rsp_iov.iov_base);
5946
5947         if (is_replayable_error(rc) &&
5948             smb2_should_replay(tcon, &retries, &cur_sleep))
5949                 goto replay_again;
5950
5951         return rc;
5952 }
5953
5954 int
5955 smb2_lockv(const unsigned int xid, struct cifs_tcon *tcon,
5956            const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
5957            const __u32 num_lock, struct smb2_lock_element *buf)
5958 {
5959         struct smb_rqst rqst;
5960         int rc = 0;
5961         struct smb2_lock_req *req = NULL;
5962         struct kvec iov[2];
5963         struct kvec rsp_iov;
5964         int resp_buf_type;
5965         unsigned int count;
5966         int flags = CIFS_NO_RSP_BUF;
5967         unsigned int total_len;
5968         struct TCP_Server_Info *server;
5969         int retries = 0, cur_sleep = 1;
5970
5971 replay_again:
5972         /* reinitialize for possible replay */
5973         flags = CIFS_NO_RSP_BUF;
5974         server = cifs_pick_channel(tcon->ses);
5975
5976         cifs_dbg(FYI, "smb2_lockv num lock %d\n", num_lock);
5977
5978         rc = smb2_plain_req_init(SMB2_LOCK, tcon, server,
5979                                  (void **) &req, &total_len);
5980         if (rc)
5981                 return rc;
5982
5983         if (smb3_encryption_required(tcon))
5984                 flags |= CIFS_TRANSFORM_REQ;
5985
5986         req->hdr.Id.SyncId.ProcessId = cpu_to_le32(pid);
5987         req->LockCount = cpu_to_le16(num_lock);
5988
5989         req->PersistentFileId = persist_fid;
5990         req->VolatileFileId = volatile_fid;
5991
5992         count = num_lock * sizeof(struct smb2_lock_element);
5993
5994         iov[0].iov_base = (char *)req;
5995         iov[0].iov_len = total_len - sizeof(struct smb2_lock_element);
5996         iov[1].iov_base = (char *)buf;
5997         iov[1].iov_len = count;
5998
5999         cifs_stats_inc(&tcon->stats.cifs_stats.num_locks);
6000
6001         memset(&rqst, 0, sizeof(struct smb_rqst));
6002         rqst.rq_iov = iov;
6003         rqst.rq_nvec = 2;
6004
6005         if (retries)
6006                 smb2_set_replay(server, &rqst);
6007
6008         rc = cifs_send_recv(xid, tcon->ses, server,
6009                             &rqst, &resp_buf_type, flags,
6010                             &rsp_iov);
6011         cifs_small_buf_release(req);
6012         if (rc) {
6013                 cifs_dbg(FYI, "Send error in smb2_lockv = %d\n", rc);
6014                 cifs_stats_fail_inc(tcon, SMB2_LOCK_HE);
6015                 trace_smb3_lock_err(xid, persist_fid, tcon->tid,
6016                                     tcon->ses->Suid, rc);
6017         }
6018
6019         if (is_replayable_error(rc) &&
6020             smb2_should_replay(tcon, &retries, &cur_sleep))
6021                 goto replay_again;
6022
6023         return rc;
6024 }
6025
6026 int
6027 SMB2_lock(const unsigned int xid, struct cifs_tcon *tcon,
6028           const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
6029           const __u64 length, const __u64 offset, const __u32 lock_flags,
6030           const bool wait)
6031 {
6032         struct smb2_lock_element lock;
6033
6034         lock.Offset = cpu_to_le64(offset);
6035         lock.Length = cpu_to_le64(length);
6036         lock.Flags = cpu_to_le32(lock_flags);
6037         if (!wait && lock_flags != SMB2_LOCKFLAG_UNLOCK)
6038                 lock.Flags |= cpu_to_le32(SMB2_LOCKFLAG_FAIL_IMMEDIATELY);
6039
6040         return smb2_lockv(xid, tcon, persist_fid, volatile_fid, pid, 1, &lock);
6041 }
6042
6043 int
6044 SMB2_lease_break(const unsigned int xid, struct cifs_tcon *tcon,
6045                  __u8 *lease_key, const __le32 lease_state)
6046 {
6047         struct smb_rqst rqst;
6048         int rc;
6049         struct smb2_lease_ack *req = NULL;
6050         struct cifs_ses *ses = tcon->ses;
6051         int flags = CIFS_OBREAK_OP;
6052         unsigned int total_len;
6053         struct kvec iov[1];
6054         struct kvec rsp_iov;
6055         int resp_buf_type;
6056         __u64 *please_key_high;
6057         __u64 *please_key_low;
6058         struct TCP_Server_Info *server = cifs_pick_channel(tcon->ses);
6059
6060         cifs_dbg(FYI, "SMB2_lease_break\n");
6061         rc = smb2_plain_req_init(SMB2_OPLOCK_BREAK, tcon, server,
6062                                  (void **) &req, &total_len);
6063         if (rc)
6064                 return rc;
6065
6066         if (smb3_encryption_required(tcon))
6067                 flags |= CIFS_TRANSFORM_REQ;
6068
6069         req->hdr.CreditRequest = cpu_to_le16(1);
6070         req->StructureSize = cpu_to_le16(36);
6071         total_len += 12;
6072
6073         memcpy(req->LeaseKey, lease_key, 16);
6074         req->LeaseState = lease_state;
6075
6076         flags |= CIFS_NO_RSP_BUF;
6077
6078         iov[0].iov_base = (char *)req;
6079         iov[0].iov_len = total_len;
6080
6081         memset(&rqst, 0, sizeof(struct smb_rqst));
6082         rqst.rq_iov = iov;
6083         rqst.rq_nvec = 1;
6084
6085         rc = cifs_send_recv(xid, ses, server,
6086                             &rqst, &resp_buf_type, flags, &rsp_iov);
6087         cifs_small_buf_release(req);
6088
6089         please_key_low = (__u64 *)lease_key;
6090         please_key_high = (__u64 *)(lease_key+8);
6091         if (rc) {
6092                 cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
6093                 trace_smb3_lease_err(le32_to_cpu(lease_state), tcon->tid,
6094                         ses->Suid, *please_key_low, *please_key_high, rc);
6095                 cifs_dbg(FYI, "Send error in Lease Break = %d\n", rc);
6096         } else
6097                 trace_smb3_lease_done(le32_to_cpu(lease_state), tcon->tid,
6098                         ses->Suid, *please_key_low, *please_key_high);
6099
6100         return rc;
6101 }