smb3: display max smb3 requests in flight at any one time
[linux-2.6-microblaze.git] / fs / cifs / smb2ops.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  SMB2 version specific operations
4  *
5  *  Copyright (c) 2012, Jeff Layton <jlayton@redhat.com>
6  */
7
8 #include <linux/pagemap.h>
9 #include <linux/vfs.h>
10 #include <linux/falloc.h>
11 #include <linux/scatterlist.h>
12 #include <linux/uuid.h>
13 #include <crypto/aead.h>
14 #include "cifsglob.h"
15 #include "smb2pdu.h"
16 #include "smb2proto.h"
17 #include "cifsproto.h"
18 #include "cifs_debug.h"
19 #include "cifs_unicode.h"
20 #include "smb2status.h"
21 #include "smb2glob.h"
22 #include "cifs_ioctl.h"
23 #include "smbdirect.h"
24
25 /* Change credits for different ops and return the total number of credits */
26 static int
27 change_conf(struct TCP_Server_Info *server)
28 {
29         server->credits += server->echo_credits + server->oplock_credits;
30         server->oplock_credits = server->echo_credits = 0;
31         switch (server->credits) {
32         case 0:
33                 return 0;
34         case 1:
35                 server->echoes = false;
36                 server->oplocks = false;
37                 break;
38         case 2:
39                 server->echoes = true;
40                 server->oplocks = false;
41                 server->echo_credits = 1;
42                 break;
43         default:
44                 server->echoes = true;
45                 if (enable_oplocks) {
46                         server->oplocks = true;
47                         server->oplock_credits = 1;
48                 } else
49                         server->oplocks = false;
50
51                 server->echo_credits = 1;
52         }
53         server->credits -= server->echo_credits + server->oplock_credits;
54         return server->credits + server->echo_credits + server->oplock_credits;
55 }
56
57 static void
58 smb2_add_credits(struct TCP_Server_Info *server,
59                  const struct cifs_credits *credits, const int optype)
60 {
61         int *val, rc = -1;
62         unsigned int add = credits->value;
63         unsigned int instance = credits->instance;
64         bool reconnect_detected = false;
65
66         spin_lock(&server->req_lock);
67         val = server->ops->get_credits_field(server, optype);
68
69         /* eg found case where write overlapping reconnect messed up credits */
70         if (((optype & CIFS_OP_MASK) == CIFS_NEG_OP) && (*val != 0))
71                 trace_smb3_reconnect_with_invalid_credits(server->CurrentMid,
72                         server->hostname, *val);
73         if ((instance == 0) || (instance == server->reconnect_instance))
74                 *val += add;
75         else
76                 reconnect_detected = true;
77
78         if (*val > 65000) {
79                 *val = 65000; /* Don't get near 64K credits, avoid srv bugs */
80                 printk_once(KERN_WARNING "server overflowed SMB3 credits\n");
81         }
82         server->in_flight--;
83         if (server->in_flight == 0 && (optype & CIFS_OP_MASK) != CIFS_NEG_OP)
84                 rc = change_conf(server);
85         /*
86          * Sometimes server returns 0 credits on oplock break ack - we need to
87          * rebalance credits in this case.
88          */
89         else if (server->in_flight > 0 && server->oplock_credits == 0 &&
90                  server->oplocks) {
91                 if (server->credits > 1) {
92                         server->credits--;
93                         server->oplock_credits++;
94                 }
95         }
96         spin_unlock(&server->req_lock);
97         wake_up(&server->request_q);
98
99         if (reconnect_detected)
100                 cifs_dbg(FYI, "trying to put %d credits from the old server instance %d\n",
101                          add, instance);
102
103         if (server->tcpStatus == CifsNeedReconnect
104             || server->tcpStatus == CifsExiting)
105                 return;
106
107         switch (rc) {
108         case -1:
109                 /* change_conf hasn't been executed */
110                 break;
111         case 0:
112                 cifs_server_dbg(VFS, "Possible client or server bug - zero credits\n");
113                 break;
114         case 1:
115                 cifs_server_dbg(VFS, "disabling echoes and oplocks\n");
116                 break;
117         case 2:
118                 cifs_dbg(FYI, "disabling oplocks\n");
119                 break;
120         default:
121                 cifs_dbg(FYI, "add %u credits total=%d\n", add, rc);
122         }
123 }
124
125 static void
126 smb2_set_credits(struct TCP_Server_Info *server, const int val)
127 {
128         spin_lock(&server->req_lock);
129         server->credits = val;
130         if (val == 1)
131                 server->reconnect_instance++;
132         spin_unlock(&server->req_lock);
133         /* don't log while holding the lock */
134         if (val == 1)
135                 cifs_dbg(FYI, "set credits to 1 due to smb2 reconnect\n");
136 }
137
138 static int *
139 smb2_get_credits_field(struct TCP_Server_Info *server, const int optype)
140 {
141         switch (optype) {
142         case CIFS_ECHO_OP:
143                 return &server->echo_credits;
144         case CIFS_OBREAK_OP:
145                 return &server->oplock_credits;
146         default:
147                 return &server->credits;
148         }
149 }
150
151 static unsigned int
152 smb2_get_credits(struct mid_q_entry *mid)
153 {
154         struct smb2_sync_hdr *shdr = (struct smb2_sync_hdr *)mid->resp_buf;
155
156         if (mid->mid_state == MID_RESPONSE_RECEIVED
157             || mid->mid_state == MID_RESPONSE_MALFORMED)
158                 return le16_to_cpu(shdr->CreditRequest);
159
160         return 0;
161 }
162
163 static int
164 smb2_wait_mtu_credits(struct TCP_Server_Info *server, unsigned int size,
165                       unsigned int *num, struct cifs_credits *credits)
166 {
167         int rc = 0;
168         unsigned int scredits;
169
170         spin_lock(&server->req_lock);
171         while (1) {
172                 if (server->credits <= 0) {
173                         spin_unlock(&server->req_lock);
174                         cifs_num_waiters_inc(server);
175                         rc = wait_event_killable(server->request_q,
176                                 has_credits(server, &server->credits, 1));
177                         cifs_num_waiters_dec(server);
178                         if (rc)
179                                 return rc;
180                         spin_lock(&server->req_lock);
181                 } else {
182                         if (server->tcpStatus == CifsExiting) {
183                                 spin_unlock(&server->req_lock);
184                                 return -ENOENT;
185                         }
186
187                         scredits = server->credits;
188                         /* can deadlock with reopen */
189                         if (scredits <= 8) {
190                                 *num = SMB2_MAX_BUFFER_SIZE;
191                                 credits->value = 0;
192                                 credits->instance = 0;
193                                 break;
194                         }
195
196                         /* leave some credits for reopen and other ops */
197                         scredits -= 8;
198                         *num = min_t(unsigned int, size,
199                                      scredits * SMB2_MAX_BUFFER_SIZE);
200
201                         credits->value =
202                                 DIV_ROUND_UP(*num, SMB2_MAX_BUFFER_SIZE);
203                         credits->instance = server->reconnect_instance;
204                         server->credits -= credits->value;
205                         server->in_flight++;
206                         if (server->in_flight > server->max_in_flight)
207                                 server->max_in_flight = server->in_flight;
208                         break;
209                 }
210         }
211         spin_unlock(&server->req_lock);
212         return rc;
213 }
214
215 static int
216 smb2_adjust_credits(struct TCP_Server_Info *server,
217                     struct cifs_credits *credits,
218                     const unsigned int payload_size)
219 {
220         int new_val = DIV_ROUND_UP(payload_size, SMB2_MAX_BUFFER_SIZE);
221
222         if (!credits->value || credits->value == new_val)
223                 return 0;
224
225         if (credits->value < new_val) {
226                 WARN_ONCE(1, "request has less credits (%d) than required (%d)",
227                           credits->value, new_val);
228                 return -ENOTSUPP;
229         }
230
231         spin_lock(&server->req_lock);
232
233         if (server->reconnect_instance != credits->instance) {
234                 spin_unlock(&server->req_lock);
235                 cifs_server_dbg(VFS, "trying to return %d credits to old session\n",
236                          credits->value - new_val);
237                 return -EAGAIN;
238         }
239
240         server->credits += credits->value - new_val;
241         spin_unlock(&server->req_lock);
242         wake_up(&server->request_q);
243         credits->value = new_val;
244         return 0;
245 }
246
247 static __u64
248 smb2_get_next_mid(struct TCP_Server_Info *server)
249 {
250         __u64 mid;
251         /* for SMB2 we need the current value */
252         spin_lock(&GlobalMid_Lock);
253         mid = server->CurrentMid++;
254         spin_unlock(&GlobalMid_Lock);
255         return mid;
256 }
257
258 static void
259 smb2_revert_current_mid(struct TCP_Server_Info *server, const unsigned int val)
260 {
261         spin_lock(&GlobalMid_Lock);
262         if (server->CurrentMid >= val)
263                 server->CurrentMid -= val;
264         spin_unlock(&GlobalMid_Lock);
265 }
266
267 static struct mid_q_entry *
268 smb2_find_mid(struct TCP_Server_Info *server, char *buf)
269 {
270         struct mid_q_entry *mid;
271         struct smb2_sync_hdr *shdr = (struct smb2_sync_hdr *)buf;
272         __u64 wire_mid = le64_to_cpu(shdr->MessageId);
273
274         if (shdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM) {
275                 cifs_server_dbg(VFS, "Encrypted frame parsing not supported yet\n");
276                 return NULL;
277         }
278
279         spin_lock(&GlobalMid_Lock);
280         list_for_each_entry(mid, &server->pending_mid_q, qhead) {
281                 if ((mid->mid == wire_mid) &&
282                     (mid->mid_state == MID_REQUEST_SUBMITTED) &&
283                     (mid->command == shdr->Command)) {
284                         kref_get(&mid->refcount);
285                         spin_unlock(&GlobalMid_Lock);
286                         return mid;
287                 }
288         }
289         spin_unlock(&GlobalMid_Lock);
290         return NULL;
291 }
292
293 static void
294 smb2_dump_detail(void *buf, struct TCP_Server_Info *server)
295 {
296 #ifdef CONFIG_CIFS_DEBUG2
297         struct smb2_sync_hdr *shdr = (struct smb2_sync_hdr *)buf;
298
299         cifs_server_dbg(VFS, "Cmd: %d Err: 0x%x Flags: 0x%x Mid: %llu Pid: %d\n",
300                  shdr->Command, shdr->Status, shdr->Flags, shdr->MessageId,
301                  shdr->ProcessId);
302         cifs_server_dbg(VFS, "smb buf %p len %u\n", buf,
303                  server->ops->calc_smb_size(buf, server));
304 #endif
305 }
306
307 static bool
308 smb2_need_neg(struct TCP_Server_Info *server)
309 {
310         return server->max_read == 0;
311 }
312
313 static int
314 smb2_negotiate(const unsigned int xid, struct cifs_ses *ses)
315 {
316         int rc;
317
318         ses->server->CurrentMid = 0;
319         rc = SMB2_negotiate(xid, ses);
320         /* BB we probably don't need to retry with modern servers */
321         if (rc == -EAGAIN)
322                 rc = -EHOSTDOWN;
323         return rc;
324 }
325
326 static unsigned int
327 smb2_negotiate_wsize(struct cifs_tcon *tcon, struct smb_vol *volume_info)
328 {
329         struct TCP_Server_Info *server = tcon->ses->server;
330         unsigned int wsize;
331
332         /* start with specified wsize, or default */
333         wsize = volume_info->wsize ? volume_info->wsize : CIFS_DEFAULT_IOSIZE;
334         wsize = min_t(unsigned int, wsize, server->max_write);
335 #ifdef CONFIG_CIFS_SMB_DIRECT
336         if (server->rdma) {
337                 if (server->sign)
338                         wsize = min_t(unsigned int,
339                                 wsize, server->smbd_conn->max_fragmented_send_size);
340                 else
341                         wsize = min_t(unsigned int,
342                                 wsize, server->smbd_conn->max_readwrite_size);
343         }
344 #endif
345         if (!(server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
346                 wsize = min_t(unsigned int, wsize, SMB2_MAX_BUFFER_SIZE);
347
348         return wsize;
349 }
350
351 static unsigned int
352 smb3_negotiate_wsize(struct cifs_tcon *tcon, struct smb_vol *volume_info)
353 {
354         struct TCP_Server_Info *server = tcon->ses->server;
355         unsigned int wsize;
356
357         /* start with specified wsize, or default */
358         wsize = volume_info->wsize ? volume_info->wsize : SMB3_DEFAULT_IOSIZE;
359         wsize = min_t(unsigned int, wsize, server->max_write);
360 #ifdef CONFIG_CIFS_SMB_DIRECT
361         if (server->rdma) {
362                 if (server->sign)
363                         wsize = min_t(unsigned int,
364                                 wsize, server->smbd_conn->max_fragmented_send_size);
365                 else
366                         wsize = min_t(unsigned int,
367                                 wsize, server->smbd_conn->max_readwrite_size);
368         }
369 #endif
370         if (!(server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
371                 wsize = min_t(unsigned int, wsize, SMB2_MAX_BUFFER_SIZE);
372
373         return wsize;
374 }
375
376 static unsigned int
377 smb2_negotiate_rsize(struct cifs_tcon *tcon, struct smb_vol *volume_info)
378 {
379         struct TCP_Server_Info *server = tcon->ses->server;
380         unsigned int rsize;
381
382         /* start with specified rsize, or default */
383         rsize = volume_info->rsize ? volume_info->rsize : CIFS_DEFAULT_IOSIZE;
384         rsize = min_t(unsigned int, rsize, server->max_read);
385 #ifdef CONFIG_CIFS_SMB_DIRECT
386         if (server->rdma) {
387                 if (server->sign)
388                         rsize = min_t(unsigned int,
389                                 rsize, server->smbd_conn->max_fragmented_recv_size);
390                 else
391                         rsize = min_t(unsigned int,
392                                 rsize, server->smbd_conn->max_readwrite_size);
393         }
394 #endif
395
396         if (!(server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
397                 rsize = min_t(unsigned int, rsize, SMB2_MAX_BUFFER_SIZE);
398
399         return rsize;
400 }
401
402 static unsigned int
403 smb3_negotiate_rsize(struct cifs_tcon *tcon, struct smb_vol *volume_info)
404 {
405         struct TCP_Server_Info *server = tcon->ses->server;
406         unsigned int rsize;
407
408         /* start with specified rsize, or default */
409         rsize = volume_info->rsize ? volume_info->rsize : SMB3_DEFAULT_IOSIZE;
410         rsize = min_t(unsigned int, rsize, server->max_read);
411 #ifdef CONFIG_CIFS_SMB_DIRECT
412         if (server->rdma) {
413                 if (server->sign)
414                         rsize = min_t(unsigned int,
415                                 rsize, server->smbd_conn->max_fragmented_recv_size);
416                 else
417                         rsize = min_t(unsigned int,
418                                 rsize, server->smbd_conn->max_readwrite_size);
419         }
420 #endif
421
422         if (!(server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
423                 rsize = min_t(unsigned int, rsize, SMB2_MAX_BUFFER_SIZE);
424
425         return rsize;
426 }
427
428 static int
429 parse_server_interfaces(struct network_interface_info_ioctl_rsp *buf,
430                         size_t buf_len,
431                         struct cifs_server_iface **iface_list,
432                         size_t *iface_count)
433 {
434         struct network_interface_info_ioctl_rsp *p;
435         struct sockaddr_in *addr4;
436         struct sockaddr_in6 *addr6;
437         struct iface_info_ipv4 *p4;
438         struct iface_info_ipv6 *p6;
439         struct cifs_server_iface *info;
440         ssize_t bytes_left;
441         size_t next = 0;
442         int nb_iface = 0;
443         int rc = 0;
444
445         *iface_list = NULL;
446         *iface_count = 0;
447
448         /*
449          * Fist pass: count and sanity check
450          */
451
452         bytes_left = buf_len;
453         p = buf;
454         while (bytes_left >= sizeof(*p)) {
455                 nb_iface++;
456                 next = le32_to_cpu(p->Next);
457                 if (!next) {
458                         bytes_left -= sizeof(*p);
459                         break;
460                 }
461                 p = (struct network_interface_info_ioctl_rsp *)((u8 *)p+next);
462                 bytes_left -= next;
463         }
464
465         if (!nb_iface) {
466                 cifs_dbg(VFS, "%s: malformed interface info\n", __func__);
467                 rc = -EINVAL;
468                 goto out;
469         }
470
471         if (bytes_left || p->Next)
472                 cifs_dbg(VFS, "%s: incomplete interface info\n", __func__);
473
474
475         /*
476          * Second pass: extract info to internal structure
477          */
478
479         *iface_list = kcalloc(nb_iface, sizeof(**iface_list), GFP_KERNEL);
480         if (!*iface_list) {
481                 rc = -ENOMEM;
482                 goto out;
483         }
484
485         info = *iface_list;
486         bytes_left = buf_len;
487         p = buf;
488         while (bytes_left >= sizeof(*p)) {
489                 info->speed = le64_to_cpu(p->LinkSpeed);
490                 info->rdma_capable = le32_to_cpu(p->Capability & RDMA_CAPABLE);
491                 info->rss_capable = le32_to_cpu(p->Capability & RSS_CAPABLE);
492
493                 cifs_dbg(FYI, "%s: adding iface %zu\n", __func__, *iface_count);
494                 cifs_dbg(FYI, "%s: speed %zu bps\n", __func__, info->speed);
495                 cifs_dbg(FYI, "%s: capabilities 0x%08x\n", __func__,
496                          le32_to_cpu(p->Capability));
497
498                 switch (p->Family) {
499                 /*
500                  * The kernel and wire socket structures have the same
501                  * layout and use network byte order but make the
502                  * conversion explicit in case either one changes.
503                  */
504                 case INTERNETWORK:
505                         addr4 = (struct sockaddr_in *)&info->sockaddr;
506                         p4 = (struct iface_info_ipv4 *)p->Buffer;
507                         addr4->sin_family = AF_INET;
508                         memcpy(&addr4->sin_addr, &p4->IPv4Address, 4);
509
510                         /* [MS-SMB2] 2.2.32.5.1.1 Clients MUST ignore these */
511                         addr4->sin_port = cpu_to_be16(CIFS_PORT);
512
513                         cifs_dbg(FYI, "%s: ipv4 %pI4\n", __func__,
514                                  &addr4->sin_addr);
515                         break;
516                 case INTERNETWORKV6:
517                         addr6 = (struct sockaddr_in6 *)&info->sockaddr;
518                         p6 = (struct iface_info_ipv6 *)p->Buffer;
519                         addr6->sin6_family = AF_INET6;
520                         memcpy(&addr6->sin6_addr, &p6->IPv6Address, 16);
521
522                         /* [MS-SMB2] 2.2.32.5.1.2 Clients MUST ignore these */
523                         addr6->sin6_flowinfo = 0;
524                         addr6->sin6_scope_id = 0;
525                         addr6->sin6_port = cpu_to_be16(CIFS_PORT);
526
527                         cifs_dbg(FYI, "%s: ipv6 %pI6\n", __func__,
528                                  &addr6->sin6_addr);
529                         break;
530                 default:
531                         cifs_dbg(VFS,
532                                  "%s: skipping unsupported socket family\n",
533                                  __func__);
534                         goto next_iface;
535                 }
536
537                 (*iface_count)++;
538                 info++;
539 next_iface:
540                 next = le32_to_cpu(p->Next);
541                 if (!next)
542                         break;
543                 p = (struct network_interface_info_ioctl_rsp *)((u8 *)p+next);
544                 bytes_left -= next;
545         }
546
547         if (!*iface_count) {
548                 rc = -EINVAL;
549                 goto out;
550         }
551
552 out:
553         if (rc) {
554                 kfree(*iface_list);
555                 *iface_count = 0;
556                 *iface_list = NULL;
557         }
558         return rc;
559 }
560
561
562 static int
563 SMB3_request_interfaces(const unsigned int xid, struct cifs_tcon *tcon)
564 {
565         int rc;
566         unsigned int ret_data_len = 0;
567         struct network_interface_info_ioctl_rsp *out_buf = NULL;
568         struct cifs_server_iface *iface_list;
569         size_t iface_count;
570         struct cifs_ses *ses = tcon->ses;
571
572         rc = SMB2_ioctl(xid, tcon, NO_FILE_ID, NO_FILE_ID,
573                         FSCTL_QUERY_NETWORK_INTERFACE_INFO, true /* is_fsctl */,
574                         NULL /* no data input */, 0 /* no data input */,
575                         CIFSMaxBufSize, (char **)&out_buf, &ret_data_len);
576         if (rc == -EOPNOTSUPP) {
577                 cifs_dbg(FYI,
578                          "server does not support query network interfaces\n");
579                 goto out;
580         } else if (rc != 0) {
581                 cifs_tcon_dbg(VFS, "error %d on ioctl to get interface list\n", rc);
582                 goto out;
583         }
584
585         rc = parse_server_interfaces(out_buf, ret_data_len,
586                                      &iface_list, &iface_count);
587         if (rc)
588                 goto out;
589
590         spin_lock(&ses->iface_lock);
591         kfree(ses->iface_list);
592         ses->iface_list = iface_list;
593         ses->iface_count = iface_count;
594         ses->iface_last_update = jiffies;
595         spin_unlock(&ses->iface_lock);
596
597 out:
598         kfree(out_buf);
599         return rc;
600 }
601
602 static void
603 smb2_close_cached_fid(struct kref *ref)
604 {
605         struct cached_fid *cfid = container_of(ref, struct cached_fid,
606                                                refcount);
607
608         if (cfid->is_valid) {
609                 cifs_dbg(FYI, "clear cached root file handle\n");
610                 SMB2_close(0, cfid->tcon, cfid->fid->persistent_fid,
611                            cfid->fid->volatile_fid);
612                 cfid->is_valid = false;
613                 cfid->file_all_info_is_valid = false;
614         }
615 }
616
617 void close_shroot(struct cached_fid *cfid)
618 {
619         mutex_lock(&cfid->fid_mutex);
620         kref_put(&cfid->refcount, smb2_close_cached_fid);
621         mutex_unlock(&cfid->fid_mutex);
622 }
623
624 void
625 smb2_cached_lease_break(struct work_struct *work)
626 {
627         struct cached_fid *cfid = container_of(work,
628                                 struct cached_fid, lease_break);
629
630         close_shroot(cfid);
631 }
632
633 /*
634  * Open the directory at the root of a share
635  */
636 int open_shroot(unsigned int xid, struct cifs_tcon *tcon, struct cifs_fid *pfid)
637 {
638         struct cifs_ses *ses = tcon->ses;
639         struct TCP_Server_Info *server = ses->server;
640         struct cifs_open_parms oparms;
641         struct smb2_create_rsp *o_rsp = NULL;
642         struct smb2_query_info_rsp *qi_rsp = NULL;
643         int resp_buftype[2];
644         struct smb_rqst rqst[2];
645         struct kvec rsp_iov[2];
646         struct kvec open_iov[SMB2_CREATE_IOV_SIZE];
647         struct kvec qi_iov[1];
648         int rc, flags = 0;
649         __le16 utf16_path = 0; /* Null - since an open of top of share */
650         u8 oplock = SMB2_OPLOCK_LEVEL_II;
651
652         mutex_lock(&tcon->crfid.fid_mutex);
653         if (tcon->crfid.is_valid) {
654                 cifs_dbg(FYI, "found a cached root file handle\n");
655                 memcpy(pfid, tcon->crfid.fid, sizeof(struct cifs_fid));
656                 kref_get(&tcon->crfid.refcount);
657                 mutex_unlock(&tcon->crfid.fid_mutex);
658                 return 0;
659         }
660
661         if (smb3_encryption_required(tcon))
662                 flags |= CIFS_TRANSFORM_REQ;
663
664         memset(rqst, 0, sizeof(rqst));
665         resp_buftype[0] = resp_buftype[1] = CIFS_NO_BUFFER;
666         memset(rsp_iov, 0, sizeof(rsp_iov));
667
668         /* Open */
669         memset(&open_iov, 0, sizeof(open_iov));
670         rqst[0].rq_iov = open_iov;
671         rqst[0].rq_nvec = SMB2_CREATE_IOV_SIZE;
672
673         oparms.tcon = tcon;
674         oparms.create_options = 0;
675         oparms.desired_access = FILE_READ_ATTRIBUTES;
676         oparms.disposition = FILE_OPEN;
677         oparms.fid = pfid;
678         oparms.reconnect = false;
679
680         rc = SMB2_open_init(tcon, &rqst[0], &oplock, &oparms, &utf16_path);
681         if (rc)
682                 goto oshr_exit;
683         smb2_set_next_command(tcon, &rqst[0]);
684
685         memset(&qi_iov, 0, sizeof(qi_iov));
686         rqst[1].rq_iov = qi_iov;
687         rqst[1].rq_nvec = 1;
688
689         rc = SMB2_query_info_init(tcon, &rqst[1], COMPOUND_FID,
690                                   COMPOUND_FID, FILE_ALL_INFORMATION,
691                                   SMB2_O_INFO_FILE, 0,
692                                   sizeof(struct smb2_file_all_info) +
693                                   PATH_MAX * 2, 0, NULL);
694         if (rc)
695                 goto oshr_exit;
696
697         smb2_set_related(&rqst[1]);
698
699         /*
700          * We do not hold the lock for the open because in case
701          * SMB2_open needs to reconnect, it will end up calling
702          * cifs_mark_open_files_invalid() which takes the lock again
703          * thus causing a deadlock
704          */
705
706         mutex_unlock(&tcon->crfid.fid_mutex);
707         rc = compound_send_recv(xid, ses, flags, 2, rqst,
708                                 resp_buftype, rsp_iov);
709         mutex_lock(&tcon->crfid.fid_mutex);
710
711         /*
712          * Now we need to check again as the cached root might have
713          * been successfully re-opened from a concurrent process
714          */
715
716         if (tcon->crfid.is_valid) {
717                 /* work was already done */
718
719                 /* stash fids for close() later */
720                 struct cifs_fid fid = {
721                         .persistent_fid = pfid->persistent_fid,
722                         .volatile_fid = pfid->volatile_fid,
723                 };
724
725                 /*
726                  * caller expects this func to set pfid to a valid
727                  * cached root, so we copy the existing one and get a
728                  * reference.
729                  */
730                 memcpy(pfid, tcon->crfid.fid, sizeof(*pfid));
731                 kref_get(&tcon->crfid.refcount);
732
733                 mutex_unlock(&tcon->crfid.fid_mutex);
734
735                 if (rc == 0) {
736                         /* close extra handle outside of crit sec */
737                         SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
738                 }
739                 goto oshr_free;
740         }
741
742         /* Cached root is still invalid, continue normaly */
743
744         if (rc)
745                 goto oshr_exit;
746
747         o_rsp = (struct smb2_create_rsp *)rsp_iov[0].iov_base;
748         oparms.fid->persistent_fid = o_rsp->PersistentFileId;
749         oparms.fid->volatile_fid = o_rsp->VolatileFileId;
750 #ifdef CONFIG_CIFS_DEBUG2
751         oparms.fid->mid = le64_to_cpu(o_rsp->sync_hdr.MessageId);
752 #endif /* CIFS_DEBUG2 */
753
754         memcpy(tcon->crfid.fid, pfid, sizeof(struct cifs_fid));
755         tcon->crfid.tcon = tcon;
756         tcon->crfid.is_valid = true;
757         kref_init(&tcon->crfid.refcount);
758
759         /* BB TBD check to see if oplock level check can be removed below */
760         if (o_rsp->OplockLevel == SMB2_OPLOCK_LEVEL_LEASE) {
761                 kref_get(&tcon->crfid.refcount);
762                 smb2_parse_contexts(server, o_rsp,
763                                 &oparms.fid->epoch,
764                                 oparms.fid->lease_key, &oplock, NULL);
765         } else
766                 goto oshr_exit;
767
768         qi_rsp = (struct smb2_query_info_rsp *)rsp_iov[1].iov_base;
769         if (le32_to_cpu(qi_rsp->OutputBufferLength) < sizeof(struct smb2_file_all_info))
770                 goto oshr_exit;
771         if (!smb2_validate_and_copy_iov(
772                                 le16_to_cpu(qi_rsp->OutputBufferOffset),
773                                 sizeof(struct smb2_file_all_info),
774                                 &rsp_iov[1], sizeof(struct smb2_file_all_info),
775                                 (char *)&tcon->crfid.file_all_info))
776                 tcon->crfid.file_all_info_is_valid = 1;
777
778 oshr_exit:
779         mutex_unlock(&tcon->crfid.fid_mutex);
780 oshr_free:
781         SMB2_open_free(&rqst[0]);
782         SMB2_query_info_free(&rqst[1]);
783         free_rsp_buf(resp_buftype[0], rsp_iov[0].iov_base);
784         free_rsp_buf(resp_buftype[1], rsp_iov[1].iov_base);
785         return rc;
786 }
787
788 static void
789 smb3_qfs_tcon(const unsigned int xid, struct cifs_tcon *tcon)
790 {
791         int rc;
792         __le16 srch_path = 0; /* Null - open root of share */
793         u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
794         struct cifs_open_parms oparms;
795         struct cifs_fid fid;
796         bool no_cached_open = tcon->nohandlecache;
797
798         oparms.tcon = tcon;
799         oparms.desired_access = FILE_READ_ATTRIBUTES;
800         oparms.disposition = FILE_OPEN;
801         oparms.create_options = 0;
802         oparms.fid = &fid;
803         oparms.reconnect = false;
804
805         if (no_cached_open)
806                 rc = SMB2_open(xid, &oparms, &srch_path, &oplock, NULL, NULL,
807                                NULL);
808         else
809                 rc = open_shroot(xid, tcon, &fid);
810
811         if (rc)
812                 return;
813
814         SMB3_request_interfaces(xid, tcon);
815
816         SMB2_QFS_attr(xid, tcon, fid.persistent_fid, fid.volatile_fid,
817                         FS_ATTRIBUTE_INFORMATION);
818         SMB2_QFS_attr(xid, tcon, fid.persistent_fid, fid.volatile_fid,
819                         FS_DEVICE_INFORMATION);
820         SMB2_QFS_attr(xid, tcon, fid.persistent_fid, fid.volatile_fid,
821                         FS_VOLUME_INFORMATION);
822         SMB2_QFS_attr(xid, tcon, fid.persistent_fid, fid.volatile_fid,
823                         FS_SECTOR_SIZE_INFORMATION); /* SMB3 specific */
824         if (no_cached_open)
825                 SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
826         else
827                 close_shroot(&tcon->crfid);
828 }
829
830 static void
831 smb2_qfs_tcon(const unsigned int xid, struct cifs_tcon *tcon)
832 {
833         int rc;
834         __le16 srch_path = 0; /* Null - open root of share */
835         u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
836         struct cifs_open_parms oparms;
837         struct cifs_fid fid;
838
839         oparms.tcon = tcon;
840         oparms.desired_access = FILE_READ_ATTRIBUTES;
841         oparms.disposition = FILE_OPEN;
842         oparms.create_options = 0;
843         oparms.fid = &fid;
844         oparms.reconnect = false;
845
846         rc = SMB2_open(xid, &oparms, &srch_path, &oplock, NULL, NULL, NULL);
847         if (rc)
848                 return;
849
850         SMB2_QFS_attr(xid, tcon, fid.persistent_fid, fid.volatile_fid,
851                         FS_ATTRIBUTE_INFORMATION);
852         SMB2_QFS_attr(xid, tcon, fid.persistent_fid, fid.volatile_fid,
853                         FS_DEVICE_INFORMATION);
854         SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
855 }
856
857 static int
858 smb2_is_path_accessible(const unsigned int xid, struct cifs_tcon *tcon,
859                         struct cifs_sb_info *cifs_sb, const char *full_path)
860 {
861         int rc;
862         __le16 *utf16_path;
863         __u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
864         struct cifs_open_parms oparms;
865         struct cifs_fid fid;
866
867         if ((*full_path == 0) && tcon->crfid.is_valid)
868                 return 0;
869
870         utf16_path = cifs_convert_path_to_utf16(full_path, cifs_sb);
871         if (!utf16_path)
872                 return -ENOMEM;
873
874         oparms.tcon = tcon;
875         oparms.desired_access = FILE_READ_ATTRIBUTES;
876         oparms.disposition = FILE_OPEN;
877         if (backup_cred(cifs_sb))
878                 oparms.create_options = CREATE_OPEN_BACKUP_INTENT;
879         else
880                 oparms.create_options = 0;
881         oparms.fid = &fid;
882         oparms.reconnect = false;
883
884         rc = SMB2_open(xid, &oparms, utf16_path, &oplock, NULL, NULL, NULL);
885         if (rc) {
886                 kfree(utf16_path);
887                 return rc;
888         }
889
890         rc = SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
891         kfree(utf16_path);
892         return rc;
893 }
894
895 static int
896 smb2_get_srv_inum(const unsigned int xid, struct cifs_tcon *tcon,
897                   struct cifs_sb_info *cifs_sb, const char *full_path,
898                   u64 *uniqueid, FILE_ALL_INFO *data)
899 {
900         *uniqueid = le64_to_cpu(data->IndexNumber);
901         return 0;
902 }
903
904 static int
905 smb2_query_file_info(const unsigned int xid, struct cifs_tcon *tcon,
906                      struct cifs_fid *fid, FILE_ALL_INFO *data)
907 {
908         int rc;
909         struct smb2_file_all_info *smb2_data;
910
911         smb2_data = kzalloc(sizeof(struct smb2_file_all_info) + PATH_MAX * 2,
912                             GFP_KERNEL);
913         if (smb2_data == NULL)
914                 return -ENOMEM;
915
916         rc = SMB2_query_info(xid, tcon, fid->persistent_fid, fid->volatile_fid,
917                              smb2_data);
918         if (!rc)
919                 move_smb2_info_to_cifs(data, smb2_data);
920         kfree(smb2_data);
921         return rc;
922 }
923
924 #ifdef CONFIG_CIFS_XATTR
925 static ssize_t
926 move_smb2_ea_to_cifs(char *dst, size_t dst_size,
927                      struct smb2_file_full_ea_info *src, size_t src_size,
928                      const unsigned char *ea_name)
929 {
930         int rc = 0;
931         unsigned int ea_name_len = ea_name ? strlen(ea_name) : 0;
932         char *name, *value;
933         size_t buf_size = dst_size;
934         size_t name_len, value_len, user_name_len;
935
936         while (src_size > 0) {
937                 name = &src->ea_data[0];
938                 name_len = (size_t)src->ea_name_length;
939                 value = &src->ea_data[src->ea_name_length + 1];
940                 value_len = (size_t)le16_to_cpu(src->ea_value_length);
941
942                 if (name_len == 0)
943                         break;
944
945                 if (src_size < 8 + name_len + 1 + value_len) {
946                         cifs_dbg(FYI, "EA entry goes beyond length of list\n");
947                         rc = -EIO;
948                         goto out;
949                 }
950
951                 if (ea_name) {
952                         if (ea_name_len == name_len &&
953                             memcmp(ea_name, name, name_len) == 0) {
954                                 rc = value_len;
955                                 if (dst_size == 0)
956                                         goto out;
957                                 if (dst_size < value_len) {
958                                         rc = -ERANGE;
959                                         goto out;
960                                 }
961                                 memcpy(dst, value, value_len);
962                                 goto out;
963                         }
964                 } else {
965                         /* 'user.' plus a terminating null */
966                         user_name_len = 5 + 1 + name_len;
967
968                         if (buf_size == 0) {
969                                 /* skip copy - calc size only */
970                                 rc += user_name_len;
971                         } else if (dst_size >= user_name_len) {
972                                 dst_size -= user_name_len;
973                                 memcpy(dst, "user.", 5);
974                                 dst += 5;
975                                 memcpy(dst, src->ea_data, name_len);
976                                 dst += name_len;
977                                 *dst = 0;
978                                 ++dst;
979                                 rc += user_name_len;
980                         } else {
981                                 /* stop before overrun buffer */
982                                 rc = -ERANGE;
983                                 break;
984                         }
985                 }
986
987                 if (!src->next_entry_offset)
988                         break;
989
990                 if (src_size < le32_to_cpu(src->next_entry_offset)) {
991                         /* stop before overrun buffer */
992                         rc = -ERANGE;
993                         break;
994                 }
995                 src_size -= le32_to_cpu(src->next_entry_offset);
996                 src = (void *)((char *)src +
997                                le32_to_cpu(src->next_entry_offset));
998         }
999
1000         /* didn't find the named attribute */
1001         if (ea_name)
1002                 rc = -ENODATA;
1003
1004 out:
1005         return (ssize_t)rc;
1006 }
1007
1008 static ssize_t
1009 smb2_query_eas(const unsigned int xid, struct cifs_tcon *tcon,
1010                const unsigned char *path, const unsigned char *ea_name,
1011                char *ea_data, size_t buf_size,
1012                struct cifs_sb_info *cifs_sb)
1013 {
1014         int rc;
1015         __le16 *utf16_path;
1016         struct kvec rsp_iov = {NULL, 0};
1017         int buftype = CIFS_NO_BUFFER;
1018         struct smb2_query_info_rsp *rsp;
1019         struct smb2_file_full_ea_info *info = NULL;
1020
1021         utf16_path = cifs_convert_path_to_utf16(path, cifs_sb);
1022         if (!utf16_path)
1023                 return -ENOMEM;
1024
1025         rc = smb2_query_info_compound(xid, tcon, utf16_path,
1026                                       FILE_READ_EA,
1027                                       FILE_FULL_EA_INFORMATION,
1028                                       SMB2_O_INFO_FILE,
1029                                       CIFSMaxBufSize -
1030                                       MAX_SMB2_CREATE_RESPONSE_SIZE -
1031                                       MAX_SMB2_CLOSE_RESPONSE_SIZE,
1032                                       &rsp_iov, &buftype, cifs_sb);
1033         if (rc) {
1034                 /*
1035                  * If ea_name is NULL (listxattr) and there are no EAs,
1036                  * return 0 as it's not an error. Otherwise, the specified
1037                  * ea_name was not found.
1038                  */
1039                 if (!ea_name && rc == -ENODATA)
1040                         rc = 0;
1041                 goto qeas_exit;
1042         }
1043
1044         rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
1045         rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
1046                                le32_to_cpu(rsp->OutputBufferLength),
1047                                &rsp_iov,
1048                                sizeof(struct smb2_file_full_ea_info));
1049         if (rc)
1050                 goto qeas_exit;
1051
1052         info = (struct smb2_file_full_ea_info *)(
1053                         le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp);
1054         rc = move_smb2_ea_to_cifs(ea_data, buf_size, info,
1055                         le32_to_cpu(rsp->OutputBufferLength), ea_name);
1056
1057  qeas_exit:
1058         kfree(utf16_path);
1059         free_rsp_buf(buftype, rsp_iov.iov_base);
1060         return rc;
1061 }
1062
1063
1064 static int
1065 smb2_set_ea(const unsigned int xid, struct cifs_tcon *tcon,
1066             const char *path, const char *ea_name, const void *ea_value,
1067             const __u16 ea_value_len, const struct nls_table *nls_codepage,
1068             struct cifs_sb_info *cifs_sb)
1069 {
1070         struct cifs_ses *ses = tcon->ses;
1071         __le16 *utf16_path = NULL;
1072         int ea_name_len = strlen(ea_name);
1073         int flags = 0;
1074         int len;
1075         struct smb_rqst rqst[3];
1076         int resp_buftype[3];
1077         struct kvec rsp_iov[3];
1078         struct kvec open_iov[SMB2_CREATE_IOV_SIZE];
1079         struct cifs_open_parms oparms;
1080         __u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
1081         struct cifs_fid fid;
1082         struct kvec si_iov[SMB2_SET_INFO_IOV_SIZE];
1083         unsigned int size[1];
1084         void *data[1];
1085         struct smb2_file_full_ea_info *ea = NULL;
1086         struct kvec close_iov[1];
1087         int rc;
1088
1089         if (smb3_encryption_required(tcon))
1090                 flags |= CIFS_TRANSFORM_REQ;
1091
1092         if (ea_name_len > 255)
1093                 return -EINVAL;
1094
1095         utf16_path = cifs_convert_path_to_utf16(path, cifs_sb);
1096         if (!utf16_path)
1097                 return -ENOMEM;
1098
1099         memset(rqst, 0, sizeof(rqst));
1100         resp_buftype[0] = resp_buftype[1] = resp_buftype[2] = CIFS_NO_BUFFER;
1101         memset(rsp_iov, 0, sizeof(rsp_iov));
1102
1103         if (ses->server->ops->query_all_EAs) {
1104                 if (!ea_value) {
1105                         rc = ses->server->ops->query_all_EAs(xid, tcon, path,
1106                                                              ea_name, NULL, 0,
1107                                                              cifs_sb);
1108                         if (rc == -ENODATA)
1109                                 goto sea_exit;
1110                 }
1111         }
1112
1113         /* Open */
1114         memset(&open_iov, 0, sizeof(open_iov));
1115         rqst[0].rq_iov = open_iov;
1116         rqst[0].rq_nvec = SMB2_CREATE_IOV_SIZE;
1117
1118         memset(&oparms, 0, sizeof(oparms));
1119         oparms.tcon = tcon;
1120         oparms.desired_access = FILE_WRITE_EA;
1121         oparms.disposition = FILE_OPEN;
1122         if (backup_cred(cifs_sb))
1123                 oparms.create_options = CREATE_OPEN_BACKUP_INTENT;
1124         else
1125                 oparms.create_options = 0;
1126         oparms.fid = &fid;
1127         oparms.reconnect = false;
1128
1129         rc = SMB2_open_init(tcon, &rqst[0], &oplock, &oparms, utf16_path);
1130         if (rc)
1131                 goto sea_exit;
1132         smb2_set_next_command(tcon, &rqst[0]);
1133
1134
1135         /* Set Info */
1136         memset(&si_iov, 0, sizeof(si_iov));
1137         rqst[1].rq_iov = si_iov;
1138         rqst[1].rq_nvec = 1;
1139
1140         len = sizeof(ea) + ea_name_len + ea_value_len + 1;
1141         ea = kzalloc(len, GFP_KERNEL);
1142         if (ea == NULL) {
1143                 rc = -ENOMEM;
1144                 goto sea_exit;
1145         }
1146
1147         ea->ea_name_length = ea_name_len;
1148         ea->ea_value_length = cpu_to_le16(ea_value_len);
1149         memcpy(ea->ea_data, ea_name, ea_name_len + 1);
1150         memcpy(ea->ea_data + ea_name_len + 1, ea_value, ea_value_len);
1151
1152         size[0] = len;
1153         data[0] = ea;
1154
1155         rc = SMB2_set_info_init(tcon, &rqst[1], COMPOUND_FID,
1156                                 COMPOUND_FID, current->tgid,
1157                                 FILE_FULL_EA_INFORMATION,
1158                                 SMB2_O_INFO_FILE, 0, data, size);
1159         smb2_set_next_command(tcon, &rqst[1]);
1160         smb2_set_related(&rqst[1]);
1161
1162
1163         /* Close */
1164         memset(&close_iov, 0, sizeof(close_iov));
1165         rqst[2].rq_iov = close_iov;
1166         rqst[2].rq_nvec = 1;
1167         rc = SMB2_close_init(tcon, &rqst[2], COMPOUND_FID, COMPOUND_FID);
1168         smb2_set_related(&rqst[2]);
1169
1170         rc = compound_send_recv(xid, ses, flags, 3, rqst,
1171                                 resp_buftype, rsp_iov);
1172
1173  sea_exit:
1174         kfree(ea);
1175         kfree(utf16_path);
1176         SMB2_open_free(&rqst[0]);
1177         SMB2_set_info_free(&rqst[1]);
1178         SMB2_close_free(&rqst[2]);
1179         free_rsp_buf(resp_buftype[0], rsp_iov[0].iov_base);
1180         free_rsp_buf(resp_buftype[1], rsp_iov[1].iov_base);
1181         free_rsp_buf(resp_buftype[2], rsp_iov[2].iov_base);
1182         return rc;
1183 }
1184 #endif
1185
1186 static bool
1187 smb2_can_echo(struct TCP_Server_Info *server)
1188 {
1189         return server->echoes;
1190 }
1191
1192 static void
1193 smb2_clear_stats(struct cifs_tcon *tcon)
1194 {
1195         int i;
1196
1197         for (i = 0; i < NUMBER_OF_SMB2_COMMANDS; i++) {
1198                 atomic_set(&tcon->stats.smb2_stats.smb2_com_sent[i], 0);
1199                 atomic_set(&tcon->stats.smb2_stats.smb2_com_failed[i], 0);
1200         }
1201 }
1202
1203 static void
1204 smb2_dump_share_caps(struct seq_file *m, struct cifs_tcon *tcon)
1205 {
1206         seq_puts(m, "\n\tShare Capabilities:");
1207         if (tcon->capabilities & SMB2_SHARE_CAP_DFS)
1208                 seq_puts(m, " DFS,");
1209         if (tcon->capabilities & SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY)
1210                 seq_puts(m, " CONTINUOUS AVAILABILITY,");
1211         if (tcon->capabilities & SMB2_SHARE_CAP_SCALEOUT)
1212                 seq_puts(m, " SCALEOUT,");
1213         if (tcon->capabilities & SMB2_SHARE_CAP_CLUSTER)
1214                 seq_puts(m, " CLUSTER,");
1215         if (tcon->capabilities & SMB2_SHARE_CAP_ASYMMETRIC)
1216                 seq_puts(m, " ASYMMETRIC,");
1217         if (tcon->capabilities == 0)
1218                 seq_puts(m, " None");
1219         if (tcon->ss_flags & SSINFO_FLAGS_ALIGNED_DEVICE)
1220                 seq_puts(m, " Aligned,");
1221         if (tcon->ss_flags & SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE)
1222                 seq_puts(m, " Partition Aligned,");
1223         if (tcon->ss_flags & SSINFO_FLAGS_NO_SEEK_PENALTY)
1224                 seq_puts(m, " SSD,");
1225         if (tcon->ss_flags & SSINFO_FLAGS_TRIM_ENABLED)
1226                 seq_puts(m, " TRIM-support,");
1227
1228         seq_printf(m, "\tShare Flags: 0x%x", tcon->share_flags);
1229         seq_printf(m, "\n\ttid: 0x%x", tcon->tid);
1230         if (tcon->perf_sector_size)
1231                 seq_printf(m, "\tOptimal sector size: 0x%x",
1232                            tcon->perf_sector_size);
1233         seq_printf(m, "\tMaximal Access: 0x%x", tcon->maximal_access);
1234 }
1235
1236 static void
1237 smb2_print_stats(struct seq_file *m, struct cifs_tcon *tcon)
1238 {
1239         atomic_t *sent = tcon->stats.smb2_stats.smb2_com_sent;
1240         atomic_t *failed = tcon->stats.smb2_stats.smb2_com_failed;
1241
1242         /*
1243          *  Can't display SMB2_NEGOTIATE, SESSION_SETUP, LOGOFF, CANCEL and ECHO
1244          *  totals (requests sent) since those SMBs are per-session not per tcon
1245          */
1246         seq_printf(m, "\nBytes read: %llu  Bytes written: %llu",
1247                    (long long)(tcon->bytes_read),
1248                    (long long)(tcon->bytes_written));
1249         seq_printf(m, "\nOpen files: %d total (local), %d open on server",
1250                    atomic_read(&tcon->num_local_opens),
1251                    atomic_read(&tcon->num_remote_opens));
1252         seq_printf(m, "\nTreeConnects: %d total %d failed",
1253                    atomic_read(&sent[SMB2_TREE_CONNECT_HE]),
1254                    atomic_read(&failed[SMB2_TREE_CONNECT_HE]));
1255         seq_printf(m, "\nTreeDisconnects: %d total %d failed",
1256                    atomic_read(&sent[SMB2_TREE_DISCONNECT_HE]),
1257                    atomic_read(&failed[SMB2_TREE_DISCONNECT_HE]));
1258         seq_printf(m, "\nCreates: %d total %d failed",
1259                    atomic_read(&sent[SMB2_CREATE_HE]),
1260                    atomic_read(&failed[SMB2_CREATE_HE]));
1261         seq_printf(m, "\nCloses: %d total %d failed",
1262                    atomic_read(&sent[SMB2_CLOSE_HE]),
1263                    atomic_read(&failed[SMB2_CLOSE_HE]));
1264         seq_printf(m, "\nFlushes: %d total %d failed",
1265                    atomic_read(&sent[SMB2_FLUSH_HE]),
1266                    atomic_read(&failed[SMB2_FLUSH_HE]));
1267         seq_printf(m, "\nReads: %d total %d failed",
1268                    atomic_read(&sent[SMB2_READ_HE]),
1269                    atomic_read(&failed[SMB2_READ_HE]));
1270         seq_printf(m, "\nWrites: %d total %d failed",
1271                    atomic_read(&sent[SMB2_WRITE_HE]),
1272                    atomic_read(&failed[SMB2_WRITE_HE]));
1273         seq_printf(m, "\nLocks: %d total %d failed",
1274                    atomic_read(&sent[SMB2_LOCK_HE]),
1275                    atomic_read(&failed[SMB2_LOCK_HE]));
1276         seq_printf(m, "\nIOCTLs: %d total %d failed",
1277                    atomic_read(&sent[SMB2_IOCTL_HE]),
1278                    atomic_read(&failed[SMB2_IOCTL_HE]));
1279         seq_printf(m, "\nQueryDirectories: %d total %d failed",
1280                    atomic_read(&sent[SMB2_QUERY_DIRECTORY_HE]),
1281                    atomic_read(&failed[SMB2_QUERY_DIRECTORY_HE]));
1282         seq_printf(m, "\nChangeNotifies: %d total %d failed",
1283                    atomic_read(&sent[SMB2_CHANGE_NOTIFY_HE]),
1284                    atomic_read(&failed[SMB2_CHANGE_NOTIFY_HE]));
1285         seq_printf(m, "\nQueryInfos: %d total %d failed",
1286                    atomic_read(&sent[SMB2_QUERY_INFO_HE]),
1287                    atomic_read(&failed[SMB2_QUERY_INFO_HE]));
1288         seq_printf(m, "\nSetInfos: %d total %d failed",
1289                    atomic_read(&sent[SMB2_SET_INFO_HE]),
1290                    atomic_read(&failed[SMB2_SET_INFO_HE]));
1291         seq_printf(m, "\nOplockBreaks: %d sent %d failed",
1292                    atomic_read(&sent[SMB2_OPLOCK_BREAK_HE]),
1293                    atomic_read(&failed[SMB2_OPLOCK_BREAK_HE]));
1294 }
1295
1296 static void
1297 smb2_set_fid(struct cifsFileInfo *cfile, struct cifs_fid *fid, __u32 oplock)
1298 {
1299         struct cifsInodeInfo *cinode = CIFS_I(d_inode(cfile->dentry));
1300         struct TCP_Server_Info *server = tlink_tcon(cfile->tlink)->ses->server;
1301
1302         cfile->fid.persistent_fid = fid->persistent_fid;
1303         cfile->fid.volatile_fid = fid->volatile_fid;
1304 #ifdef CONFIG_CIFS_DEBUG2
1305         cfile->fid.mid = fid->mid;
1306 #endif /* CIFS_DEBUG2 */
1307         server->ops->set_oplock_level(cinode, oplock, fid->epoch,
1308                                       &fid->purge_cache);
1309         cinode->can_cache_brlcks = CIFS_CACHE_WRITE(cinode);
1310         memcpy(cfile->fid.create_guid, fid->create_guid, 16);
1311 }
1312
1313 static void
1314 smb2_close_file(const unsigned int xid, struct cifs_tcon *tcon,
1315                 struct cifs_fid *fid)
1316 {
1317         SMB2_close(xid, tcon, fid->persistent_fid, fid->volatile_fid);
1318 }
1319
1320 static int
1321 SMB2_request_res_key(const unsigned int xid, struct cifs_tcon *tcon,
1322                      u64 persistent_fid, u64 volatile_fid,
1323                      struct copychunk_ioctl *pcchunk)
1324 {
1325         int rc;
1326         unsigned int ret_data_len;
1327         struct resume_key_req *res_key;
1328
1329         rc = SMB2_ioctl(xid, tcon, persistent_fid, volatile_fid,
1330                         FSCTL_SRV_REQUEST_RESUME_KEY, true /* is_fsctl */,
1331                         NULL, 0 /* no input */, CIFSMaxBufSize,
1332                         (char **)&res_key, &ret_data_len);
1333
1334         if (rc) {
1335                 cifs_tcon_dbg(VFS, "refcpy ioctl error %d getting resume key\n", rc);
1336                 goto req_res_key_exit;
1337         }
1338         if (ret_data_len < sizeof(struct resume_key_req)) {
1339                 cifs_tcon_dbg(VFS, "Invalid refcopy resume key length\n");
1340                 rc = -EINVAL;
1341                 goto req_res_key_exit;
1342         }
1343         memcpy(pcchunk->SourceKey, res_key->ResumeKey, COPY_CHUNK_RES_KEY_SIZE);
1344
1345 req_res_key_exit:
1346         kfree(res_key);
1347         return rc;
1348 }
1349
1350 static int
1351 smb2_ioctl_query_info(const unsigned int xid,
1352                       struct cifs_tcon *tcon,
1353                       __le16 *path, int is_dir,
1354                       unsigned long p)
1355 {
1356         struct cifs_ses *ses = tcon->ses;
1357         char __user *arg = (char __user *)p;
1358         struct smb_query_info qi;
1359         struct smb_query_info __user *pqi;
1360         int rc = 0;
1361         int flags = 0;
1362         struct smb2_query_info_rsp *qi_rsp = NULL;
1363         struct smb2_ioctl_rsp *io_rsp = NULL;
1364         void *buffer = NULL;
1365         struct smb_rqst rqst[3];
1366         int resp_buftype[3];
1367         struct kvec rsp_iov[3];
1368         struct kvec open_iov[SMB2_CREATE_IOV_SIZE];
1369         struct cifs_open_parms oparms;
1370         u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
1371         struct cifs_fid fid;
1372         struct kvec qi_iov[1];
1373         struct kvec io_iov[SMB2_IOCTL_IOV_SIZE];
1374         struct kvec si_iov[SMB2_SET_INFO_IOV_SIZE];
1375         struct kvec close_iov[1];
1376         unsigned int size[2];
1377         void *data[2];
1378
1379         memset(rqst, 0, sizeof(rqst));
1380         resp_buftype[0] = resp_buftype[1] = resp_buftype[2] = CIFS_NO_BUFFER;
1381         memset(rsp_iov, 0, sizeof(rsp_iov));
1382
1383         if (copy_from_user(&qi, arg, sizeof(struct smb_query_info)))
1384                 return -EFAULT;
1385
1386         if (qi.output_buffer_length > 1024)
1387                 return -EINVAL;
1388
1389         if (!ses || !(ses->server))
1390                 return -EIO;
1391
1392         if (smb3_encryption_required(tcon))
1393                 flags |= CIFS_TRANSFORM_REQ;
1394
1395         buffer = kmalloc(qi.output_buffer_length, GFP_KERNEL);
1396         if (buffer == NULL)
1397                 return -ENOMEM;
1398
1399         if (copy_from_user(buffer, arg + sizeof(struct smb_query_info),
1400                            qi.output_buffer_length)) {
1401                 rc = -EFAULT;
1402                 goto iqinf_exit;
1403         }
1404
1405         /* Open */
1406         memset(&open_iov, 0, sizeof(open_iov));
1407         rqst[0].rq_iov = open_iov;
1408         rqst[0].rq_nvec = SMB2_CREATE_IOV_SIZE;
1409
1410         memset(&oparms, 0, sizeof(oparms));
1411         oparms.tcon = tcon;
1412         oparms.disposition = FILE_OPEN;
1413         if (is_dir)
1414                 oparms.create_options = CREATE_NOT_FILE;
1415         else
1416                 oparms.create_options = CREATE_NOT_DIR;
1417         oparms.fid = &fid;
1418         oparms.reconnect = false;
1419
1420         if (qi.flags & PASSTHRU_FSCTL) {
1421                 switch (qi.info_type & FSCTL_DEVICE_ACCESS_MASK) {
1422                 case FSCTL_DEVICE_ACCESS_FILE_READ_WRITE_ACCESS:
1423                         oparms.desired_access = FILE_READ_DATA | FILE_WRITE_DATA | FILE_READ_ATTRIBUTES | SYNCHRONIZE;
1424                         break;
1425                 case FSCTL_DEVICE_ACCESS_FILE_ANY_ACCESS:
1426                         oparms.desired_access = GENERIC_ALL;
1427                         break;
1428                 case FSCTL_DEVICE_ACCESS_FILE_READ_ACCESS:
1429                         oparms.desired_access = GENERIC_READ;
1430                         break;
1431                 case FSCTL_DEVICE_ACCESS_FILE_WRITE_ACCESS:
1432                         oparms.desired_access = GENERIC_WRITE;
1433                         break;
1434                 }
1435         } else if (qi.flags & PASSTHRU_SET_INFO) {
1436                 oparms.desired_access = GENERIC_WRITE;
1437         } else {
1438                 oparms.desired_access = FILE_READ_ATTRIBUTES | READ_CONTROL;
1439         }
1440
1441         rc = SMB2_open_init(tcon, &rqst[0], &oplock, &oparms, path);
1442         if (rc)
1443                 goto iqinf_exit;
1444         smb2_set_next_command(tcon, &rqst[0]);
1445
1446         /* Query */
1447         if (qi.flags & PASSTHRU_FSCTL) {
1448                 /* Can eventually relax perm check since server enforces too */
1449                 if (!capable(CAP_SYS_ADMIN))
1450                         rc = -EPERM;
1451                 else  {
1452                         memset(&io_iov, 0, sizeof(io_iov));
1453                         rqst[1].rq_iov = io_iov;
1454                         rqst[1].rq_nvec = SMB2_IOCTL_IOV_SIZE;
1455
1456                         rc = SMB2_ioctl_init(tcon, &rqst[1],
1457                                              COMPOUND_FID, COMPOUND_FID,
1458                                              qi.info_type, true, buffer,
1459                                              qi.output_buffer_length,
1460                                              CIFSMaxBufSize);
1461                 }
1462         } else if (qi.flags == PASSTHRU_SET_INFO) {
1463                 /* Can eventually relax perm check since server enforces too */
1464                 if (!capable(CAP_SYS_ADMIN))
1465                         rc = -EPERM;
1466                 else  {
1467                         memset(&si_iov, 0, sizeof(si_iov));
1468                         rqst[1].rq_iov = si_iov;
1469                         rqst[1].rq_nvec = 1;
1470
1471                         size[0] = 8;
1472                         data[0] = buffer;
1473
1474                         rc = SMB2_set_info_init(tcon, &rqst[1],
1475                                         COMPOUND_FID, COMPOUND_FID,
1476                                         current->tgid,
1477                                         FILE_END_OF_FILE_INFORMATION,
1478                                         SMB2_O_INFO_FILE, 0, data, size);
1479                 }
1480         } else if (qi.flags == PASSTHRU_QUERY_INFO) {
1481                 memset(&qi_iov, 0, sizeof(qi_iov));
1482                 rqst[1].rq_iov = qi_iov;
1483                 rqst[1].rq_nvec = 1;
1484
1485                 rc = SMB2_query_info_init(tcon, &rqst[1], COMPOUND_FID,
1486                                   COMPOUND_FID, qi.file_info_class,
1487                                   qi.info_type, qi.additional_information,
1488                                   qi.input_buffer_length,
1489                                   qi.output_buffer_length, buffer);
1490         } else { /* unknown flags */
1491                 cifs_tcon_dbg(VFS, "invalid passthru query flags: 0x%x\n", qi.flags);
1492                 rc = -EINVAL;
1493         }
1494
1495         if (rc)
1496                 goto iqinf_exit;
1497         smb2_set_next_command(tcon, &rqst[1]);
1498         smb2_set_related(&rqst[1]);
1499
1500         /* Close */
1501         memset(&close_iov, 0, sizeof(close_iov));
1502         rqst[2].rq_iov = close_iov;
1503         rqst[2].rq_nvec = 1;
1504
1505         rc = SMB2_close_init(tcon, &rqst[2], COMPOUND_FID, COMPOUND_FID);
1506         if (rc)
1507                 goto iqinf_exit;
1508         smb2_set_related(&rqst[2]);
1509
1510         rc = compound_send_recv(xid, ses, flags, 3, rqst,
1511                                 resp_buftype, rsp_iov);
1512         if (rc)
1513                 goto iqinf_exit;
1514         if (qi.flags & PASSTHRU_FSCTL) {
1515                 pqi = (struct smb_query_info __user *)arg;
1516                 io_rsp = (struct smb2_ioctl_rsp *)rsp_iov[1].iov_base;
1517                 if (le32_to_cpu(io_rsp->OutputCount) < qi.input_buffer_length)
1518                         qi.input_buffer_length = le32_to_cpu(io_rsp->OutputCount);
1519                 if (qi.input_buffer_length > 0 &&
1520                     le32_to_cpu(io_rsp->OutputOffset) + qi.input_buffer_length > rsp_iov[1].iov_len) {
1521                         rc = -EFAULT;
1522                         goto iqinf_exit;
1523                 }
1524                 if (copy_to_user(&pqi->input_buffer_length, &qi.input_buffer_length,
1525                                  sizeof(qi.input_buffer_length))) {
1526                         rc = -EFAULT;
1527                         goto iqinf_exit;
1528                 }
1529                 if (copy_to_user((void __user *)pqi + sizeof(struct smb_query_info),
1530                                  (const void *)io_rsp + le32_to_cpu(io_rsp->OutputOffset),
1531                                  qi.input_buffer_length)) {
1532                         rc = -EFAULT;
1533                         goto iqinf_exit;
1534                 }
1535         } else {
1536                 pqi = (struct smb_query_info __user *)arg;
1537                 qi_rsp = (struct smb2_query_info_rsp *)rsp_iov[1].iov_base;
1538                 if (le32_to_cpu(qi_rsp->OutputBufferLength) < qi.input_buffer_length)
1539                         qi.input_buffer_length = le32_to_cpu(qi_rsp->OutputBufferLength);
1540                 if (copy_to_user(&pqi->input_buffer_length, &qi.input_buffer_length,
1541                                  sizeof(qi.input_buffer_length))) {
1542                         rc = -EFAULT;
1543                         goto iqinf_exit;
1544                 }
1545                 if (copy_to_user(pqi + 1, qi_rsp->Buffer, qi.input_buffer_length)) {
1546                         rc = -EFAULT;
1547                         goto iqinf_exit;
1548                 }
1549         }
1550
1551  iqinf_exit:
1552         kfree(buffer);
1553         SMB2_open_free(&rqst[0]);
1554         if (qi.flags & PASSTHRU_FSCTL)
1555                 SMB2_ioctl_free(&rqst[1]);
1556         else
1557                 SMB2_query_info_free(&rqst[1]);
1558
1559         SMB2_close_free(&rqst[2]);
1560         free_rsp_buf(resp_buftype[0], rsp_iov[0].iov_base);
1561         free_rsp_buf(resp_buftype[1], rsp_iov[1].iov_base);
1562         free_rsp_buf(resp_buftype[2], rsp_iov[2].iov_base);
1563         return rc;
1564 }
1565
1566 static ssize_t
1567 smb2_copychunk_range(const unsigned int xid,
1568                         struct cifsFileInfo *srcfile,
1569                         struct cifsFileInfo *trgtfile, u64 src_off,
1570                         u64 len, u64 dest_off)
1571 {
1572         int rc;
1573         unsigned int ret_data_len;
1574         struct copychunk_ioctl *pcchunk;
1575         struct copychunk_ioctl_rsp *retbuf = NULL;
1576         struct cifs_tcon *tcon;
1577         int chunks_copied = 0;
1578         bool chunk_sizes_updated = false;
1579         ssize_t bytes_written, total_bytes_written = 0;
1580
1581         pcchunk = kmalloc(sizeof(struct copychunk_ioctl), GFP_KERNEL);
1582
1583         if (pcchunk == NULL)
1584                 return -ENOMEM;
1585
1586         cifs_dbg(FYI, "%s: about to call request res key\n", __func__);
1587         /* Request a key from the server to identify the source of the copy */
1588         rc = SMB2_request_res_key(xid, tlink_tcon(srcfile->tlink),
1589                                 srcfile->fid.persistent_fid,
1590                                 srcfile->fid.volatile_fid, pcchunk);
1591
1592         /* Note: request_res_key sets res_key null only if rc !=0 */
1593         if (rc)
1594                 goto cchunk_out;
1595
1596         /* For now array only one chunk long, will make more flexible later */
1597         pcchunk->ChunkCount = cpu_to_le32(1);
1598         pcchunk->Reserved = 0;
1599         pcchunk->Reserved2 = 0;
1600
1601         tcon = tlink_tcon(trgtfile->tlink);
1602
1603         while (len > 0) {
1604                 pcchunk->SourceOffset = cpu_to_le64(src_off);
1605                 pcchunk->TargetOffset = cpu_to_le64(dest_off);
1606                 pcchunk->Length =
1607                         cpu_to_le32(min_t(u32, len, tcon->max_bytes_chunk));
1608
1609                 /* Request server copy to target from src identified by key */
1610                 rc = SMB2_ioctl(xid, tcon, trgtfile->fid.persistent_fid,
1611                         trgtfile->fid.volatile_fid, FSCTL_SRV_COPYCHUNK_WRITE,
1612                         true /* is_fsctl */, (char *)pcchunk,
1613                         sizeof(struct copychunk_ioctl), CIFSMaxBufSize,
1614                         (char **)&retbuf, &ret_data_len);
1615                 if (rc == 0) {
1616                         if (ret_data_len !=
1617                                         sizeof(struct copychunk_ioctl_rsp)) {
1618                                 cifs_tcon_dbg(VFS, "invalid cchunk response size\n");
1619                                 rc = -EIO;
1620                                 goto cchunk_out;
1621                         }
1622                         if (retbuf->TotalBytesWritten == 0) {
1623                                 cifs_dbg(FYI, "no bytes copied\n");
1624                                 rc = -EIO;
1625                                 goto cchunk_out;
1626                         }
1627                         /*
1628                          * Check if server claimed to write more than we asked
1629                          */
1630                         if (le32_to_cpu(retbuf->TotalBytesWritten) >
1631                             le32_to_cpu(pcchunk->Length)) {
1632                                 cifs_tcon_dbg(VFS, "invalid copy chunk response\n");
1633                                 rc = -EIO;
1634                                 goto cchunk_out;
1635                         }
1636                         if (le32_to_cpu(retbuf->ChunksWritten) != 1) {
1637                                 cifs_tcon_dbg(VFS, "invalid num chunks written\n");
1638                                 rc = -EIO;
1639                                 goto cchunk_out;
1640                         }
1641                         chunks_copied++;
1642
1643                         bytes_written = le32_to_cpu(retbuf->TotalBytesWritten);
1644                         src_off += bytes_written;
1645                         dest_off += bytes_written;
1646                         len -= bytes_written;
1647                         total_bytes_written += bytes_written;
1648
1649                         cifs_dbg(FYI, "Chunks %d PartialChunk %d Total %zu\n",
1650                                 le32_to_cpu(retbuf->ChunksWritten),
1651                                 le32_to_cpu(retbuf->ChunkBytesWritten),
1652                                 bytes_written);
1653                 } else if (rc == -EINVAL) {
1654                         if (ret_data_len != sizeof(struct copychunk_ioctl_rsp))
1655                                 goto cchunk_out;
1656
1657                         cifs_dbg(FYI, "MaxChunks %d BytesChunk %d MaxCopy %d\n",
1658                                 le32_to_cpu(retbuf->ChunksWritten),
1659                                 le32_to_cpu(retbuf->ChunkBytesWritten),
1660                                 le32_to_cpu(retbuf->TotalBytesWritten));
1661
1662                         /*
1663                          * Check if this is the first request using these sizes,
1664                          * (ie check if copy succeed once with original sizes
1665                          * and check if the server gave us different sizes after
1666                          * we already updated max sizes on previous request).
1667                          * if not then why is the server returning an error now
1668                          */
1669                         if ((chunks_copied != 0) || chunk_sizes_updated)
1670                                 goto cchunk_out;
1671
1672                         /* Check that server is not asking us to grow size */
1673                         if (le32_to_cpu(retbuf->ChunkBytesWritten) <
1674                                         tcon->max_bytes_chunk)
1675                                 tcon->max_bytes_chunk =
1676                                         le32_to_cpu(retbuf->ChunkBytesWritten);
1677                         else
1678                                 goto cchunk_out; /* server gave us bogus size */
1679
1680                         /* No need to change MaxChunks since already set to 1 */
1681                         chunk_sizes_updated = true;
1682                 } else
1683                         goto cchunk_out;
1684         }
1685
1686 cchunk_out:
1687         kfree(pcchunk);
1688         kfree(retbuf);
1689         if (rc)
1690                 return rc;
1691         else
1692                 return total_bytes_written;
1693 }
1694
1695 static int
1696 smb2_flush_file(const unsigned int xid, struct cifs_tcon *tcon,
1697                 struct cifs_fid *fid)
1698 {
1699         return SMB2_flush(xid, tcon, fid->persistent_fid, fid->volatile_fid);
1700 }
1701
1702 static unsigned int
1703 smb2_read_data_offset(char *buf)
1704 {
1705         struct smb2_read_rsp *rsp = (struct smb2_read_rsp *)buf;
1706
1707         return rsp->DataOffset;
1708 }
1709
1710 static unsigned int
1711 smb2_read_data_length(char *buf, bool in_remaining)
1712 {
1713         struct smb2_read_rsp *rsp = (struct smb2_read_rsp *)buf;
1714
1715         if (in_remaining)
1716                 return le32_to_cpu(rsp->DataRemaining);
1717
1718         return le32_to_cpu(rsp->DataLength);
1719 }
1720
1721
1722 static int
1723 smb2_sync_read(const unsigned int xid, struct cifs_fid *pfid,
1724                struct cifs_io_parms *parms, unsigned int *bytes_read,
1725                char **buf, int *buf_type)
1726 {
1727         parms->persistent_fid = pfid->persistent_fid;
1728         parms->volatile_fid = pfid->volatile_fid;
1729         return SMB2_read(xid, parms, bytes_read, buf, buf_type);
1730 }
1731
1732 static int
1733 smb2_sync_write(const unsigned int xid, struct cifs_fid *pfid,
1734                 struct cifs_io_parms *parms, unsigned int *written,
1735                 struct kvec *iov, unsigned long nr_segs)
1736 {
1737
1738         parms->persistent_fid = pfid->persistent_fid;
1739         parms->volatile_fid = pfid->volatile_fid;
1740         return SMB2_write(xid, parms, written, iov, nr_segs);
1741 }
1742
1743 /* Set or clear the SPARSE_FILE attribute based on value passed in setsparse */
1744 static bool smb2_set_sparse(const unsigned int xid, struct cifs_tcon *tcon,
1745                 struct cifsFileInfo *cfile, struct inode *inode, __u8 setsparse)
1746 {
1747         struct cifsInodeInfo *cifsi;
1748         int rc;
1749
1750         cifsi = CIFS_I(inode);
1751
1752         /* if file already sparse don't bother setting sparse again */
1753         if ((cifsi->cifsAttrs & FILE_ATTRIBUTE_SPARSE_FILE) && setsparse)
1754                 return true; /* already sparse */
1755
1756         if (!(cifsi->cifsAttrs & FILE_ATTRIBUTE_SPARSE_FILE) && !setsparse)
1757                 return true; /* already not sparse */
1758
1759         /*
1760          * Can't check for sparse support on share the usual way via the
1761          * FS attribute info (FILE_SUPPORTS_SPARSE_FILES) on the share
1762          * since Samba server doesn't set the flag on the share, yet
1763          * supports the set sparse FSCTL and returns sparse correctly
1764          * in the file attributes. If we fail setting sparse though we
1765          * mark that server does not support sparse files for this share
1766          * to avoid repeatedly sending the unsupported fsctl to server
1767          * if the file is repeatedly extended.
1768          */
1769         if (tcon->broken_sparse_sup)
1770                 return false;
1771
1772         rc = SMB2_ioctl(xid, tcon, cfile->fid.persistent_fid,
1773                         cfile->fid.volatile_fid, FSCTL_SET_SPARSE,
1774                         true /* is_fctl */,
1775                         &setsparse, 1, CIFSMaxBufSize, NULL, NULL);
1776         if (rc) {
1777                 tcon->broken_sparse_sup = true;
1778                 cifs_dbg(FYI, "set sparse rc = %d\n", rc);
1779                 return false;
1780         }
1781
1782         if (setsparse)
1783                 cifsi->cifsAttrs |= FILE_ATTRIBUTE_SPARSE_FILE;
1784         else
1785                 cifsi->cifsAttrs &= (~FILE_ATTRIBUTE_SPARSE_FILE);
1786
1787         return true;
1788 }
1789
1790 static int
1791 smb2_set_file_size(const unsigned int xid, struct cifs_tcon *tcon,
1792                    struct cifsFileInfo *cfile, __u64 size, bool set_alloc)
1793 {
1794         __le64 eof = cpu_to_le64(size);
1795         struct inode *inode;
1796
1797         /*
1798          * If extending file more than one page make sparse. Many Linux fs
1799          * make files sparse by default when extending via ftruncate
1800          */
1801         inode = d_inode(cfile->dentry);
1802
1803         if (!set_alloc && (size > inode->i_size + 8192)) {
1804                 __u8 set_sparse = 1;
1805
1806                 /* whether set sparse succeeds or not, extend the file */
1807                 smb2_set_sparse(xid, tcon, cfile, inode, set_sparse);
1808         }
1809
1810         return SMB2_set_eof(xid, tcon, cfile->fid.persistent_fid,
1811                             cfile->fid.volatile_fid, cfile->pid, &eof);
1812 }
1813
1814 static int
1815 smb2_duplicate_extents(const unsigned int xid,
1816                         struct cifsFileInfo *srcfile,
1817                         struct cifsFileInfo *trgtfile, u64 src_off,
1818                         u64 len, u64 dest_off)
1819 {
1820         int rc;
1821         unsigned int ret_data_len;
1822         struct duplicate_extents_to_file dup_ext_buf;
1823         struct cifs_tcon *tcon = tlink_tcon(trgtfile->tlink);
1824
1825         /* server fileays advertise duplicate extent support with this flag */
1826         if ((le32_to_cpu(tcon->fsAttrInfo.Attributes) &
1827              FILE_SUPPORTS_BLOCK_REFCOUNTING) == 0)
1828                 return -EOPNOTSUPP;
1829
1830         dup_ext_buf.VolatileFileHandle = srcfile->fid.volatile_fid;
1831         dup_ext_buf.PersistentFileHandle = srcfile->fid.persistent_fid;
1832         dup_ext_buf.SourceFileOffset = cpu_to_le64(src_off);
1833         dup_ext_buf.TargetFileOffset = cpu_to_le64(dest_off);
1834         dup_ext_buf.ByteCount = cpu_to_le64(len);
1835         cifs_dbg(FYI, "Duplicate extents: src off %lld dst off %lld len %lld\n",
1836                 src_off, dest_off, len);
1837
1838         rc = smb2_set_file_size(xid, tcon, trgtfile, dest_off + len, false);
1839         if (rc)
1840                 goto duplicate_extents_out;
1841
1842         rc = SMB2_ioctl(xid, tcon, trgtfile->fid.persistent_fid,
1843                         trgtfile->fid.volatile_fid,
1844                         FSCTL_DUPLICATE_EXTENTS_TO_FILE,
1845                         true /* is_fsctl */,
1846                         (char *)&dup_ext_buf,
1847                         sizeof(struct duplicate_extents_to_file),
1848                         CIFSMaxBufSize, NULL,
1849                         &ret_data_len);
1850
1851         if (ret_data_len > 0)
1852                 cifs_dbg(FYI, "Non-zero response length in duplicate extents\n");
1853
1854 duplicate_extents_out:
1855         return rc;
1856 }
1857
1858 static int
1859 smb2_set_compression(const unsigned int xid, struct cifs_tcon *tcon,
1860                    struct cifsFileInfo *cfile)
1861 {
1862         return SMB2_set_compression(xid, tcon, cfile->fid.persistent_fid,
1863                             cfile->fid.volatile_fid);
1864 }
1865
1866 static int
1867 smb3_set_integrity(const unsigned int xid, struct cifs_tcon *tcon,
1868                    struct cifsFileInfo *cfile)
1869 {
1870         struct fsctl_set_integrity_information_req integr_info;
1871         unsigned int ret_data_len;
1872
1873         integr_info.ChecksumAlgorithm = cpu_to_le16(CHECKSUM_TYPE_UNCHANGED);
1874         integr_info.Flags = 0;
1875         integr_info.Reserved = 0;
1876
1877         return SMB2_ioctl(xid, tcon, cfile->fid.persistent_fid,
1878                         cfile->fid.volatile_fid,
1879                         FSCTL_SET_INTEGRITY_INFORMATION,
1880                         true /* is_fsctl */,
1881                         (char *)&integr_info,
1882                         sizeof(struct fsctl_set_integrity_information_req),
1883                         CIFSMaxBufSize, NULL,
1884                         &ret_data_len);
1885
1886 }
1887
1888 /* GMT Token is @GMT-YYYY.MM.DD-HH.MM.SS Unicode which is 48 bytes + null */
1889 #define GMT_TOKEN_SIZE 50
1890
1891 #define MIN_SNAPSHOT_ARRAY_SIZE 16 /* See MS-SMB2 section 3.3.5.15.1 */
1892
1893 /*
1894  * Input buffer contains (empty) struct smb_snapshot array with size filled in
1895  * For output see struct SRV_SNAPSHOT_ARRAY in MS-SMB2 section 2.2.32.2
1896  */
1897 static int
1898 smb3_enum_snapshots(const unsigned int xid, struct cifs_tcon *tcon,
1899                    struct cifsFileInfo *cfile, void __user *ioc_buf)
1900 {
1901         char *retbuf = NULL;
1902         unsigned int ret_data_len = 0;
1903         int rc;
1904         u32 max_response_size;
1905         struct smb_snapshot_array snapshot_in;
1906
1907         /*
1908          * On the first query to enumerate the list of snapshots available
1909          * for this volume the buffer begins with 0 (number of snapshots
1910          * which can be returned is zero since at that point we do not know
1911          * how big the buffer needs to be). On the second query,
1912          * it (ret_data_len) is set to number of snapshots so we can
1913          * know to set the maximum response size larger (see below).
1914          */
1915         if (get_user(ret_data_len, (unsigned int __user *)ioc_buf))
1916                 return -EFAULT;
1917
1918         /*
1919          * Note that for snapshot queries that servers like Azure expect that
1920          * the first query be minimal size (and just used to get the number/size
1921          * of previous versions) so response size must be specified as EXACTLY
1922          * sizeof(struct snapshot_array) which is 16 when rounded up to multiple
1923          * of eight bytes.
1924          */
1925         if (ret_data_len == 0)
1926                 max_response_size = MIN_SNAPSHOT_ARRAY_SIZE;
1927         else
1928                 max_response_size = CIFSMaxBufSize;
1929
1930         rc = SMB2_ioctl(xid, tcon, cfile->fid.persistent_fid,
1931                         cfile->fid.volatile_fid,
1932                         FSCTL_SRV_ENUMERATE_SNAPSHOTS,
1933                         true /* is_fsctl */,
1934                         NULL, 0 /* no input data */, max_response_size,
1935                         (char **)&retbuf,
1936                         &ret_data_len);
1937         cifs_dbg(FYI, "enum snaphots ioctl returned %d and ret buflen is %d\n",
1938                         rc, ret_data_len);
1939         if (rc)
1940                 return rc;
1941
1942         if (ret_data_len && (ioc_buf != NULL) && (retbuf != NULL)) {
1943                 /* Fixup buffer */
1944                 if (copy_from_user(&snapshot_in, ioc_buf,
1945                     sizeof(struct smb_snapshot_array))) {
1946                         rc = -EFAULT;
1947                         kfree(retbuf);
1948                         return rc;
1949                 }
1950
1951                 /*
1952                  * Check for min size, ie not large enough to fit even one GMT
1953                  * token (snapshot).  On the first ioctl some users may pass in
1954                  * smaller size (or zero) to simply get the size of the array
1955                  * so the user space caller can allocate sufficient memory
1956                  * and retry the ioctl again with larger array size sufficient
1957                  * to hold all of the snapshot GMT tokens on the second try.
1958                  */
1959                 if (snapshot_in.snapshot_array_size < GMT_TOKEN_SIZE)
1960                         ret_data_len = sizeof(struct smb_snapshot_array);
1961
1962                 /*
1963                  * We return struct SRV_SNAPSHOT_ARRAY, followed by
1964                  * the snapshot array (of 50 byte GMT tokens) each
1965                  * representing an available previous version of the data
1966                  */
1967                 if (ret_data_len > (snapshot_in.snapshot_array_size +
1968                                         sizeof(struct smb_snapshot_array)))
1969                         ret_data_len = snapshot_in.snapshot_array_size +
1970                                         sizeof(struct smb_snapshot_array);
1971
1972                 if (copy_to_user(ioc_buf, retbuf, ret_data_len))
1973                         rc = -EFAULT;
1974         }
1975
1976         kfree(retbuf);
1977         return rc;
1978 }
1979
1980 static int
1981 smb2_query_dir_first(const unsigned int xid, struct cifs_tcon *tcon,
1982                      const char *path, struct cifs_sb_info *cifs_sb,
1983                      struct cifs_fid *fid, __u16 search_flags,
1984                      struct cifs_search_info *srch_inf)
1985 {
1986         __le16 *utf16_path;
1987         int rc;
1988         __u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
1989         struct cifs_open_parms oparms;
1990
1991         utf16_path = cifs_convert_path_to_utf16(path, cifs_sb);
1992         if (!utf16_path)
1993                 return -ENOMEM;
1994
1995         oparms.tcon = tcon;
1996         oparms.desired_access = FILE_READ_ATTRIBUTES | FILE_READ_DATA;
1997         oparms.disposition = FILE_OPEN;
1998         if (backup_cred(cifs_sb))
1999                 oparms.create_options = CREATE_OPEN_BACKUP_INTENT;
2000         else
2001                 oparms.create_options = 0;
2002         oparms.fid = fid;
2003         oparms.reconnect = false;
2004
2005         rc = SMB2_open(xid, &oparms, utf16_path, &oplock, NULL, NULL, NULL);
2006         kfree(utf16_path);
2007         if (rc) {
2008                 cifs_dbg(FYI, "open dir failed rc=%d\n", rc);
2009                 return rc;
2010         }
2011
2012         srch_inf->entries_in_buffer = 0;
2013         srch_inf->index_of_last_entry = 2;
2014
2015         rc = SMB2_query_directory(xid, tcon, fid->persistent_fid,
2016                                   fid->volatile_fid, 0, srch_inf);
2017         if (rc) {
2018                 cifs_dbg(FYI, "query directory failed rc=%d\n", rc);
2019                 SMB2_close(xid, tcon, fid->persistent_fid, fid->volatile_fid);
2020         }
2021         return rc;
2022 }
2023
2024 static int
2025 smb2_query_dir_next(const unsigned int xid, struct cifs_tcon *tcon,
2026                     struct cifs_fid *fid, __u16 search_flags,
2027                     struct cifs_search_info *srch_inf)
2028 {
2029         return SMB2_query_directory(xid, tcon, fid->persistent_fid,
2030                                     fid->volatile_fid, 0, srch_inf);
2031 }
2032
2033 static int
2034 smb2_close_dir(const unsigned int xid, struct cifs_tcon *tcon,
2035                struct cifs_fid *fid)
2036 {
2037         return SMB2_close(xid, tcon, fid->persistent_fid, fid->volatile_fid);
2038 }
2039
2040 /*
2041  * If we negotiate SMB2 protocol and get STATUS_PENDING - update
2042  * the number of credits and return true. Otherwise - return false.
2043  */
2044 static bool
2045 smb2_is_status_pending(char *buf, struct TCP_Server_Info *server)
2046 {
2047         struct smb2_sync_hdr *shdr = (struct smb2_sync_hdr *)buf;
2048
2049         if (shdr->Status != STATUS_PENDING)
2050                 return false;
2051
2052         if (shdr->CreditRequest) {
2053                 spin_lock(&server->req_lock);
2054                 server->credits += le16_to_cpu(shdr->CreditRequest);
2055                 spin_unlock(&server->req_lock);
2056                 wake_up(&server->request_q);
2057         }
2058
2059         return true;
2060 }
2061
2062 static bool
2063 smb2_is_session_expired(char *buf)
2064 {
2065         struct smb2_sync_hdr *shdr = (struct smb2_sync_hdr *)buf;
2066
2067         if (shdr->Status != STATUS_NETWORK_SESSION_EXPIRED &&
2068             shdr->Status != STATUS_USER_SESSION_DELETED)
2069                 return false;
2070
2071         trace_smb3_ses_expired(shdr->TreeId, shdr->SessionId,
2072                                le16_to_cpu(shdr->Command),
2073                                le64_to_cpu(shdr->MessageId));
2074         cifs_dbg(FYI, "Session expired or deleted\n");
2075
2076         return true;
2077 }
2078
2079 static int
2080 smb2_oplock_response(struct cifs_tcon *tcon, struct cifs_fid *fid,
2081                      struct cifsInodeInfo *cinode)
2082 {
2083         if (tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_LEASING)
2084                 return SMB2_lease_break(0, tcon, cinode->lease_key,
2085                                         smb2_get_lease_state(cinode));
2086
2087         return SMB2_oplock_break(0, tcon, fid->persistent_fid,
2088                                  fid->volatile_fid,
2089                                  CIFS_CACHE_READ(cinode) ? 1 : 0);
2090 }
2091
2092 void
2093 smb2_set_related(struct smb_rqst *rqst)
2094 {
2095         struct smb2_sync_hdr *shdr;
2096
2097         shdr = (struct smb2_sync_hdr *)(rqst->rq_iov[0].iov_base);
2098         if (shdr == NULL) {
2099                 cifs_dbg(FYI, "shdr NULL in smb2_set_related\n");
2100                 return;
2101         }
2102         shdr->Flags |= SMB2_FLAGS_RELATED_OPERATIONS;
2103 }
2104
2105 char smb2_padding[7] = {0, 0, 0, 0, 0, 0, 0};
2106
2107 void
2108 smb2_set_next_command(struct cifs_tcon *tcon, struct smb_rqst *rqst)
2109 {
2110         struct smb2_sync_hdr *shdr;
2111         struct cifs_ses *ses = tcon->ses;
2112         struct TCP_Server_Info *server = ses->server;
2113         unsigned long len = smb_rqst_len(server, rqst);
2114         int i, num_padding;
2115
2116         shdr = (struct smb2_sync_hdr *)(rqst->rq_iov[0].iov_base);
2117         if (shdr == NULL) {
2118                 cifs_dbg(FYI, "shdr NULL in smb2_set_next_command\n");
2119                 return;
2120         }
2121
2122         /* SMB headers in a compound are 8 byte aligned. */
2123
2124         /* No padding needed */
2125         if (!(len & 7))
2126                 goto finished;
2127
2128         num_padding = 8 - (len & 7);
2129         if (!smb3_encryption_required(tcon)) {
2130                 /*
2131                  * If we do not have encryption then we can just add an extra
2132                  * iov for the padding.
2133                  */
2134                 rqst->rq_iov[rqst->rq_nvec].iov_base = smb2_padding;
2135                 rqst->rq_iov[rqst->rq_nvec].iov_len = num_padding;
2136                 rqst->rq_nvec++;
2137                 len += num_padding;
2138         } else {
2139                 /*
2140                  * We can not add a small padding iov for the encryption case
2141                  * because the encryption framework can not handle the padding
2142                  * iovs.
2143                  * We have to flatten this into a single buffer and add
2144                  * the padding to it.
2145                  */
2146                 for (i = 1; i < rqst->rq_nvec; i++) {
2147                         memcpy(rqst->rq_iov[0].iov_base +
2148                                rqst->rq_iov[0].iov_len,
2149                                rqst->rq_iov[i].iov_base,
2150                                rqst->rq_iov[i].iov_len);
2151                         rqst->rq_iov[0].iov_len += rqst->rq_iov[i].iov_len;
2152                 }
2153                 memset(rqst->rq_iov[0].iov_base + rqst->rq_iov[0].iov_len,
2154                        0, num_padding);
2155                 rqst->rq_iov[0].iov_len += num_padding;
2156                 len += num_padding;
2157                 rqst->rq_nvec = 1;
2158         }
2159
2160  finished:
2161         shdr->NextCommand = cpu_to_le32(len);
2162 }
2163
2164 /*
2165  * Passes the query info response back to the caller on success.
2166  * Caller need to free this with free_rsp_buf().
2167  */
2168 int
2169 smb2_query_info_compound(const unsigned int xid, struct cifs_tcon *tcon,
2170                          __le16 *utf16_path, u32 desired_access,
2171                          u32 class, u32 type, u32 output_len,
2172                          struct kvec *rsp, int *buftype,
2173                          struct cifs_sb_info *cifs_sb)
2174 {
2175         struct cifs_ses *ses = tcon->ses;
2176         int flags = 0;
2177         struct smb_rqst rqst[3];
2178         int resp_buftype[3];
2179         struct kvec rsp_iov[3];
2180         struct kvec open_iov[SMB2_CREATE_IOV_SIZE];
2181         struct kvec qi_iov[1];
2182         struct kvec close_iov[1];
2183         u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
2184         struct cifs_open_parms oparms;
2185         struct cifs_fid fid;
2186         int rc;
2187
2188         if (smb3_encryption_required(tcon))
2189                 flags |= CIFS_TRANSFORM_REQ;
2190
2191         memset(rqst, 0, sizeof(rqst));
2192         resp_buftype[0] = resp_buftype[1] = resp_buftype[2] = CIFS_NO_BUFFER;
2193         memset(rsp_iov, 0, sizeof(rsp_iov));
2194
2195         memset(&open_iov, 0, sizeof(open_iov));
2196         rqst[0].rq_iov = open_iov;
2197         rqst[0].rq_nvec = SMB2_CREATE_IOV_SIZE;
2198
2199         oparms.tcon = tcon;
2200         oparms.desired_access = desired_access;
2201         oparms.disposition = FILE_OPEN;
2202         if (cifs_sb && backup_cred(cifs_sb))
2203                 oparms.create_options = CREATE_OPEN_BACKUP_INTENT;
2204         else
2205                 oparms.create_options = 0;
2206         oparms.fid = &fid;
2207         oparms.reconnect = false;
2208
2209         rc = SMB2_open_init(tcon, &rqst[0], &oplock, &oparms, utf16_path);
2210         if (rc)
2211                 goto qic_exit;
2212         smb2_set_next_command(tcon, &rqst[0]);
2213
2214         memset(&qi_iov, 0, sizeof(qi_iov));
2215         rqst[1].rq_iov = qi_iov;
2216         rqst[1].rq_nvec = 1;
2217
2218         rc = SMB2_query_info_init(tcon, &rqst[1], COMPOUND_FID, COMPOUND_FID,
2219                                   class, type, 0,
2220                                   output_len, 0,
2221                                   NULL);
2222         if (rc)
2223                 goto qic_exit;
2224         smb2_set_next_command(tcon, &rqst[1]);
2225         smb2_set_related(&rqst[1]);
2226
2227         memset(&close_iov, 0, sizeof(close_iov));
2228         rqst[2].rq_iov = close_iov;
2229         rqst[2].rq_nvec = 1;
2230
2231         rc = SMB2_close_init(tcon, &rqst[2], COMPOUND_FID, COMPOUND_FID);
2232         if (rc)
2233                 goto qic_exit;
2234         smb2_set_related(&rqst[2]);
2235
2236         rc = compound_send_recv(xid, ses, flags, 3, rqst,
2237                                 resp_buftype, rsp_iov);
2238         if (rc) {
2239                 free_rsp_buf(resp_buftype[1], rsp_iov[1].iov_base);
2240                 goto qic_exit;
2241         }
2242         *rsp = rsp_iov[1];
2243         *buftype = resp_buftype[1];
2244
2245  qic_exit:
2246         SMB2_open_free(&rqst[0]);
2247         SMB2_query_info_free(&rqst[1]);
2248         SMB2_close_free(&rqst[2]);
2249         free_rsp_buf(resp_buftype[0], rsp_iov[0].iov_base);
2250         free_rsp_buf(resp_buftype[2], rsp_iov[2].iov_base);
2251         return rc;
2252 }
2253
2254 static int
2255 smb2_queryfs(const unsigned int xid, struct cifs_tcon *tcon,
2256              struct kstatfs *buf)
2257 {
2258         struct smb2_query_info_rsp *rsp;
2259         struct smb2_fs_full_size_info *info = NULL;
2260         __le16 utf16_path = 0; /* Null - open root of share */
2261         struct kvec rsp_iov = {NULL, 0};
2262         int buftype = CIFS_NO_BUFFER;
2263         int rc;
2264
2265
2266         rc = smb2_query_info_compound(xid, tcon, &utf16_path,
2267                                       FILE_READ_ATTRIBUTES,
2268                                       FS_FULL_SIZE_INFORMATION,
2269                                       SMB2_O_INFO_FILESYSTEM,
2270                                       sizeof(struct smb2_fs_full_size_info),
2271                                       &rsp_iov, &buftype, NULL);
2272         if (rc)
2273                 goto qfs_exit;
2274
2275         rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
2276         buf->f_type = SMB2_MAGIC_NUMBER;
2277         info = (struct smb2_fs_full_size_info *)(
2278                 le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp);
2279         rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
2280                                le32_to_cpu(rsp->OutputBufferLength),
2281                                &rsp_iov,
2282                                sizeof(struct smb2_fs_full_size_info));
2283         if (!rc)
2284                 smb2_copy_fs_info_to_kstatfs(info, buf);
2285
2286 qfs_exit:
2287         free_rsp_buf(buftype, rsp_iov.iov_base);
2288         return rc;
2289 }
2290
2291 static int
2292 smb311_queryfs(const unsigned int xid, struct cifs_tcon *tcon,
2293              struct kstatfs *buf)
2294 {
2295         int rc;
2296         __le16 srch_path = 0; /* Null - open root of share */
2297         u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
2298         struct cifs_open_parms oparms;
2299         struct cifs_fid fid;
2300
2301         if (!tcon->posix_extensions)
2302                 return smb2_queryfs(xid, tcon, buf);
2303
2304         oparms.tcon = tcon;
2305         oparms.desired_access = FILE_READ_ATTRIBUTES;
2306         oparms.disposition = FILE_OPEN;
2307         oparms.create_options = 0;
2308         oparms.fid = &fid;
2309         oparms.reconnect = false;
2310
2311         rc = SMB2_open(xid, &oparms, &srch_path, &oplock, NULL, NULL, NULL);
2312         if (rc)
2313                 return rc;
2314
2315         rc = SMB311_posix_qfs_info(xid, tcon, fid.persistent_fid,
2316                                    fid.volatile_fid, buf);
2317         buf->f_type = SMB2_MAGIC_NUMBER;
2318         SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
2319         return rc;
2320 }
2321
2322 static bool
2323 smb2_compare_fids(struct cifsFileInfo *ob1, struct cifsFileInfo *ob2)
2324 {
2325         return ob1->fid.persistent_fid == ob2->fid.persistent_fid &&
2326                ob1->fid.volatile_fid == ob2->fid.volatile_fid;
2327 }
2328
2329 static int
2330 smb2_mand_lock(const unsigned int xid, struct cifsFileInfo *cfile, __u64 offset,
2331                __u64 length, __u32 type, int lock, int unlock, bool wait)
2332 {
2333         if (unlock && !lock)
2334                 type = SMB2_LOCKFLAG_UNLOCK;
2335         return SMB2_lock(xid, tlink_tcon(cfile->tlink),
2336                          cfile->fid.persistent_fid, cfile->fid.volatile_fid,
2337                          current->tgid, length, offset, type, wait);
2338 }
2339
2340 static void
2341 smb2_get_lease_key(struct inode *inode, struct cifs_fid *fid)
2342 {
2343         memcpy(fid->lease_key, CIFS_I(inode)->lease_key, SMB2_LEASE_KEY_SIZE);
2344 }
2345
2346 static void
2347 smb2_set_lease_key(struct inode *inode, struct cifs_fid *fid)
2348 {
2349         memcpy(CIFS_I(inode)->lease_key, fid->lease_key, SMB2_LEASE_KEY_SIZE);
2350 }
2351
2352 static void
2353 smb2_new_lease_key(struct cifs_fid *fid)
2354 {
2355         generate_random_uuid(fid->lease_key);
2356 }
2357
2358 static int
2359 smb2_get_dfs_refer(const unsigned int xid, struct cifs_ses *ses,
2360                    const char *search_name,
2361                    struct dfs_info3_param **target_nodes,
2362                    unsigned int *num_of_nodes,
2363                    const struct nls_table *nls_codepage, int remap)
2364 {
2365         int rc;
2366         __le16 *utf16_path = NULL;
2367         int utf16_path_len = 0;
2368         struct cifs_tcon *tcon;
2369         struct fsctl_get_dfs_referral_req *dfs_req = NULL;
2370         struct get_dfs_referral_rsp *dfs_rsp = NULL;
2371         u32 dfs_req_size = 0, dfs_rsp_size = 0;
2372
2373         cifs_dbg(FYI, "%s: path: %s\n", __func__, search_name);
2374
2375         /*
2376          * Try to use the IPC tcon, otherwise just use any
2377          */
2378         tcon = ses->tcon_ipc;
2379         if (tcon == NULL) {
2380                 spin_lock(&cifs_tcp_ses_lock);
2381                 tcon = list_first_entry_or_null(&ses->tcon_list,
2382                                                 struct cifs_tcon,
2383                                                 tcon_list);
2384                 if (tcon)
2385                         tcon->tc_count++;
2386                 spin_unlock(&cifs_tcp_ses_lock);
2387         }
2388
2389         if (tcon == NULL) {
2390                 cifs_dbg(VFS, "session %p has no tcon available for a dfs referral request\n",
2391                          ses);
2392                 rc = -ENOTCONN;
2393                 goto out;
2394         }
2395
2396         utf16_path = cifs_strndup_to_utf16(search_name, PATH_MAX,
2397                                            &utf16_path_len,
2398                                            nls_codepage, remap);
2399         if (!utf16_path) {
2400                 rc = -ENOMEM;
2401                 goto out;
2402         }
2403
2404         dfs_req_size = sizeof(*dfs_req) + utf16_path_len;
2405         dfs_req = kzalloc(dfs_req_size, GFP_KERNEL);
2406         if (!dfs_req) {
2407                 rc = -ENOMEM;
2408                 goto out;
2409         }
2410
2411         /* Highest DFS referral version understood */
2412         dfs_req->MaxReferralLevel = DFS_VERSION;
2413
2414         /* Path to resolve in an UTF-16 null-terminated string */
2415         memcpy(dfs_req->RequestFileName, utf16_path, utf16_path_len);
2416
2417         do {
2418                 rc = SMB2_ioctl(xid, tcon, NO_FILE_ID, NO_FILE_ID,
2419                                 FSCTL_DFS_GET_REFERRALS,
2420                                 true /* is_fsctl */,
2421                                 (char *)dfs_req, dfs_req_size, CIFSMaxBufSize,
2422                                 (char **)&dfs_rsp, &dfs_rsp_size);
2423         } while (rc == -EAGAIN);
2424
2425         if (rc) {
2426                 if ((rc != -ENOENT) && (rc != -EOPNOTSUPP))
2427                         cifs_tcon_dbg(VFS, "ioctl error in %s rc=%d\n", __func__, rc);
2428                 goto out;
2429         }
2430
2431         rc = parse_dfs_referrals(dfs_rsp, dfs_rsp_size,
2432                                  num_of_nodes, target_nodes,
2433                                  nls_codepage, remap, search_name,
2434                                  true /* is_unicode */);
2435         if (rc) {
2436                 cifs_tcon_dbg(VFS, "parse error in %s rc=%d\n", __func__, rc);
2437                 goto out;
2438         }
2439
2440  out:
2441         if (tcon && !tcon->ipc) {
2442                 /* ipc tcons are not refcounted */
2443                 spin_lock(&cifs_tcp_ses_lock);
2444                 tcon->tc_count--;
2445                 spin_unlock(&cifs_tcp_ses_lock);
2446         }
2447         kfree(utf16_path);
2448         kfree(dfs_req);
2449         kfree(dfs_rsp);
2450         return rc;
2451 }
2452
2453 static int
2454 parse_reparse_posix(struct reparse_posix_data *symlink_buf,
2455                       u32 plen, char **target_path,
2456                       struct cifs_sb_info *cifs_sb)
2457 {
2458         unsigned int len;
2459
2460         /* See MS-FSCC 2.1.2.6 for the 'NFS' style reparse tags */
2461         len = le16_to_cpu(symlink_buf->ReparseDataLength);
2462
2463         if (le64_to_cpu(symlink_buf->InodeType) != NFS_SPECFILE_LNK) {
2464                 cifs_dbg(VFS, "%lld not a supported symlink type\n",
2465                         le64_to_cpu(symlink_buf->InodeType));
2466                 return -EOPNOTSUPP;
2467         }
2468
2469         *target_path = cifs_strndup_from_utf16(
2470                                 symlink_buf->PathBuffer,
2471                                 len, true, cifs_sb->local_nls);
2472         if (!(*target_path))
2473                 return -ENOMEM;
2474
2475         convert_delimiter(*target_path, '/');
2476         cifs_dbg(FYI, "%s: target path: %s\n", __func__, *target_path);
2477
2478         return 0;
2479 }
2480
2481 static int
2482 parse_reparse_symlink(struct reparse_symlink_data_buffer *symlink_buf,
2483                       u32 plen, char **target_path,
2484                       struct cifs_sb_info *cifs_sb)
2485 {
2486         unsigned int sub_len;
2487         unsigned int sub_offset;
2488
2489         /* We handle Symbolic Link reparse tag here. See: MS-FSCC 2.1.2.4 */
2490
2491         sub_offset = le16_to_cpu(symlink_buf->SubstituteNameOffset);
2492         sub_len = le16_to_cpu(symlink_buf->SubstituteNameLength);
2493         if (sub_offset + 20 > plen ||
2494             sub_offset + sub_len + 20 > plen) {
2495                 cifs_dbg(VFS, "srv returned malformed symlink buffer\n");
2496                 return -EIO;
2497         }
2498
2499         *target_path = cifs_strndup_from_utf16(
2500                                 symlink_buf->PathBuffer + sub_offset,
2501                                 sub_len, true, cifs_sb->local_nls);
2502         if (!(*target_path))
2503                 return -ENOMEM;
2504
2505         convert_delimiter(*target_path, '/');
2506         cifs_dbg(FYI, "%s: target path: %s\n", __func__, *target_path);
2507
2508         return 0;
2509 }
2510
2511 static int
2512 parse_reparse_point(struct reparse_data_buffer *buf,
2513                     u32 plen, char **target_path,
2514                     struct cifs_sb_info *cifs_sb)
2515 {
2516         if (plen < sizeof(struct reparse_data_buffer)) {
2517                 cifs_dbg(VFS, "reparse buffer is too small. Must be "
2518                          "at least 8 bytes but was %d\n", plen);
2519                 return -EIO;
2520         }
2521
2522         if (plen < le16_to_cpu(buf->ReparseDataLength) +
2523             sizeof(struct reparse_data_buffer)) {
2524                 cifs_dbg(VFS, "srv returned invalid reparse buf "
2525                          "length: %d\n", plen);
2526                 return -EIO;
2527         }
2528
2529         /* See MS-FSCC 2.1.2 */
2530         switch (le32_to_cpu(buf->ReparseTag)) {
2531         case IO_REPARSE_TAG_NFS:
2532                 return parse_reparse_posix(
2533                         (struct reparse_posix_data *)buf,
2534                         plen, target_path, cifs_sb);
2535         case IO_REPARSE_TAG_SYMLINK:
2536                 return parse_reparse_symlink(
2537                         (struct reparse_symlink_data_buffer *)buf,
2538                         plen, target_path, cifs_sb);
2539         default:
2540                 cifs_dbg(VFS, "srv returned unknown symlink buffer "
2541                          "tag:0x%08x\n", le32_to_cpu(buf->ReparseTag));
2542                 return -EOPNOTSUPP;
2543         }
2544 }
2545
2546 #define SMB2_SYMLINK_STRUCT_SIZE \
2547         (sizeof(struct smb2_err_rsp) - 1 + sizeof(struct smb2_symlink_err_rsp))
2548
2549 static int
2550 smb2_query_symlink(const unsigned int xid, struct cifs_tcon *tcon,
2551                    struct cifs_sb_info *cifs_sb, const char *full_path,
2552                    char **target_path, bool is_reparse_point)
2553 {
2554         int rc;
2555         __le16 *utf16_path = NULL;
2556         __u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
2557         struct cifs_open_parms oparms;
2558         struct cifs_fid fid;
2559         struct kvec err_iov = {NULL, 0};
2560         struct smb2_err_rsp *err_buf = NULL;
2561         struct smb2_symlink_err_rsp *symlink;
2562         unsigned int sub_len;
2563         unsigned int sub_offset;
2564         unsigned int print_len;
2565         unsigned int print_offset;
2566         int flags = 0;
2567         struct smb_rqst rqst[3];
2568         int resp_buftype[3];
2569         struct kvec rsp_iov[3];
2570         struct kvec open_iov[SMB2_CREATE_IOV_SIZE];
2571         struct kvec io_iov[SMB2_IOCTL_IOV_SIZE];
2572         struct kvec close_iov[1];
2573         struct smb2_create_rsp *create_rsp;
2574         struct smb2_ioctl_rsp *ioctl_rsp;
2575         struct reparse_data_buffer *reparse_buf;
2576         u32 plen;
2577
2578         cifs_dbg(FYI, "%s: path: %s\n", __func__, full_path);
2579
2580         *target_path = NULL;
2581
2582         if (smb3_encryption_required(tcon))
2583                 flags |= CIFS_TRANSFORM_REQ;
2584
2585         memset(rqst, 0, sizeof(rqst));
2586         resp_buftype[0] = resp_buftype[1] = resp_buftype[2] = CIFS_NO_BUFFER;
2587         memset(rsp_iov, 0, sizeof(rsp_iov));
2588
2589         utf16_path = cifs_convert_path_to_utf16(full_path, cifs_sb);
2590         if (!utf16_path)
2591                 return -ENOMEM;
2592
2593         /* Open */
2594         memset(&open_iov, 0, sizeof(open_iov));
2595         rqst[0].rq_iov = open_iov;
2596         rqst[0].rq_nvec = SMB2_CREATE_IOV_SIZE;
2597
2598         memset(&oparms, 0, sizeof(oparms));
2599         oparms.tcon = tcon;
2600         oparms.desired_access = FILE_READ_ATTRIBUTES;
2601         oparms.disposition = FILE_OPEN;
2602
2603         if (backup_cred(cifs_sb))
2604                 oparms.create_options = CREATE_OPEN_BACKUP_INTENT;
2605         else
2606                 oparms.create_options = 0;
2607         if (is_reparse_point)
2608                 oparms.create_options = OPEN_REPARSE_POINT;
2609
2610         oparms.fid = &fid;
2611         oparms.reconnect = false;
2612
2613         rc = SMB2_open_init(tcon, &rqst[0], &oplock, &oparms, utf16_path);
2614         if (rc)
2615                 goto querty_exit;
2616         smb2_set_next_command(tcon, &rqst[0]);
2617
2618
2619         /* IOCTL */
2620         memset(&io_iov, 0, sizeof(io_iov));
2621         rqst[1].rq_iov = io_iov;
2622         rqst[1].rq_nvec = SMB2_IOCTL_IOV_SIZE;
2623
2624         rc = SMB2_ioctl_init(tcon, &rqst[1], fid.persistent_fid,
2625                              fid.volatile_fid, FSCTL_GET_REPARSE_POINT,
2626                              true /* is_fctl */, NULL, 0, CIFSMaxBufSize);
2627         if (rc)
2628                 goto querty_exit;
2629
2630         smb2_set_next_command(tcon, &rqst[1]);
2631         smb2_set_related(&rqst[1]);
2632
2633
2634         /* Close */
2635         memset(&close_iov, 0, sizeof(close_iov));
2636         rqst[2].rq_iov = close_iov;
2637         rqst[2].rq_nvec = 1;
2638
2639         rc = SMB2_close_init(tcon, &rqst[2], COMPOUND_FID, COMPOUND_FID);
2640         if (rc)
2641                 goto querty_exit;
2642
2643         smb2_set_related(&rqst[2]);
2644
2645         rc = compound_send_recv(xid, tcon->ses, flags, 3, rqst,
2646                                 resp_buftype, rsp_iov);
2647
2648         create_rsp = rsp_iov[0].iov_base;
2649         if (create_rsp && create_rsp->sync_hdr.Status)
2650                 err_iov = rsp_iov[0];
2651         ioctl_rsp = rsp_iov[1].iov_base;
2652
2653         /*
2654          * Open was successful and we got an ioctl response.
2655          */
2656         if ((rc == 0) && (is_reparse_point)) {
2657                 /* See MS-FSCC 2.3.23 */
2658
2659                 reparse_buf = (struct reparse_data_buffer *)
2660                         ((char *)ioctl_rsp +
2661                          le32_to_cpu(ioctl_rsp->OutputOffset));
2662                 plen = le32_to_cpu(ioctl_rsp->OutputCount);
2663
2664                 if (plen + le32_to_cpu(ioctl_rsp->OutputOffset) >
2665                     rsp_iov[1].iov_len) {
2666                         cifs_tcon_dbg(VFS, "srv returned invalid ioctl len: %d\n",
2667                                  plen);
2668                         rc = -EIO;
2669                         goto querty_exit;
2670                 }
2671
2672                 rc = parse_reparse_point(reparse_buf, plen, target_path,
2673                                          cifs_sb);
2674                 goto querty_exit;
2675         }
2676
2677         if (!rc || !err_iov.iov_base) {
2678                 rc = -ENOENT;
2679                 goto querty_exit;
2680         }
2681
2682         err_buf = err_iov.iov_base;
2683         if (le32_to_cpu(err_buf->ByteCount) < sizeof(struct smb2_symlink_err_rsp) ||
2684             err_iov.iov_len < SMB2_SYMLINK_STRUCT_SIZE) {
2685                 rc = -EINVAL;
2686                 goto querty_exit;
2687         }
2688
2689         symlink = (struct smb2_symlink_err_rsp *)err_buf->ErrorData;
2690         if (le32_to_cpu(symlink->SymLinkErrorTag) != SYMLINK_ERROR_TAG ||
2691             le32_to_cpu(symlink->ReparseTag) != IO_REPARSE_TAG_SYMLINK) {
2692                 rc = -EINVAL;
2693                 goto querty_exit;
2694         }
2695
2696         /* open must fail on symlink - reset rc */
2697         rc = 0;
2698         sub_len = le16_to_cpu(symlink->SubstituteNameLength);
2699         sub_offset = le16_to_cpu(symlink->SubstituteNameOffset);
2700         print_len = le16_to_cpu(symlink->PrintNameLength);
2701         print_offset = le16_to_cpu(symlink->PrintNameOffset);
2702
2703         if (err_iov.iov_len < SMB2_SYMLINK_STRUCT_SIZE + sub_offset + sub_len) {
2704                 rc = -EINVAL;
2705                 goto querty_exit;
2706         }
2707
2708         if (err_iov.iov_len <
2709             SMB2_SYMLINK_STRUCT_SIZE + print_offset + print_len) {
2710                 rc = -EINVAL;
2711                 goto querty_exit;
2712         }
2713
2714         *target_path = cifs_strndup_from_utf16(
2715                                 (char *)symlink->PathBuffer + sub_offset,
2716                                 sub_len, true, cifs_sb->local_nls);
2717         if (!(*target_path)) {
2718                 rc = -ENOMEM;
2719                 goto querty_exit;
2720         }
2721         convert_delimiter(*target_path, '/');
2722         cifs_dbg(FYI, "%s: target path: %s\n", __func__, *target_path);
2723
2724  querty_exit:
2725         cifs_dbg(FYI, "query symlink rc %d\n", rc);
2726         kfree(utf16_path);
2727         SMB2_open_free(&rqst[0]);
2728         SMB2_ioctl_free(&rqst[1]);
2729         SMB2_close_free(&rqst[2]);
2730         free_rsp_buf(resp_buftype[0], rsp_iov[0].iov_base);
2731         free_rsp_buf(resp_buftype[1], rsp_iov[1].iov_base);
2732         free_rsp_buf(resp_buftype[2], rsp_iov[2].iov_base);
2733         return rc;
2734 }
2735
2736 static struct cifs_ntsd *
2737 get_smb2_acl_by_fid(struct cifs_sb_info *cifs_sb,
2738                 const struct cifs_fid *cifsfid, u32 *pacllen)
2739 {
2740         struct cifs_ntsd *pntsd = NULL;
2741         unsigned int xid;
2742         int rc = -EOPNOTSUPP;
2743         struct tcon_link *tlink = cifs_sb_tlink(cifs_sb);
2744
2745         if (IS_ERR(tlink))
2746                 return ERR_CAST(tlink);
2747
2748         xid = get_xid();
2749         cifs_dbg(FYI, "trying to get acl\n");
2750
2751         rc = SMB2_query_acl(xid, tlink_tcon(tlink), cifsfid->persistent_fid,
2752                             cifsfid->volatile_fid, (void **)&pntsd, pacllen);
2753         free_xid(xid);
2754
2755         cifs_put_tlink(tlink);
2756
2757         cifs_dbg(FYI, "%s: rc = %d ACL len %d\n", __func__, rc, *pacllen);
2758         if (rc)
2759                 return ERR_PTR(rc);
2760         return pntsd;
2761
2762 }
2763
2764 static struct cifs_ntsd *
2765 get_smb2_acl_by_path(struct cifs_sb_info *cifs_sb,
2766                 const char *path, u32 *pacllen)
2767 {
2768         struct cifs_ntsd *pntsd = NULL;
2769         u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
2770         unsigned int xid;
2771         int rc;
2772         struct cifs_tcon *tcon;
2773         struct tcon_link *tlink = cifs_sb_tlink(cifs_sb);
2774         struct cifs_fid fid;
2775         struct cifs_open_parms oparms;
2776         __le16 *utf16_path;
2777
2778         cifs_dbg(FYI, "get smb3 acl for path %s\n", path);
2779         if (IS_ERR(tlink))
2780                 return ERR_CAST(tlink);
2781
2782         tcon = tlink_tcon(tlink);
2783         xid = get_xid();
2784
2785         if (backup_cred(cifs_sb))
2786                 oparms.create_options = CREATE_OPEN_BACKUP_INTENT;
2787         else
2788                 oparms.create_options = 0;
2789
2790         utf16_path = cifs_convert_path_to_utf16(path, cifs_sb);
2791         if (!utf16_path) {
2792                 rc = -ENOMEM;
2793                 free_xid(xid);
2794                 return ERR_PTR(rc);
2795         }
2796
2797         oparms.tcon = tcon;
2798         oparms.desired_access = READ_CONTROL;
2799         oparms.disposition = FILE_OPEN;
2800         oparms.fid = &fid;
2801         oparms.reconnect = false;
2802
2803         rc = SMB2_open(xid, &oparms, utf16_path, &oplock, NULL, NULL, NULL);
2804         kfree(utf16_path);
2805         if (!rc) {
2806                 rc = SMB2_query_acl(xid, tlink_tcon(tlink), fid.persistent_fid,
2807                             fid.volatile_fid, (void **)&pntsd, pacllen);
2808                 SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
2809         }
2810
2811         cifs_put_tlink(tlink);
2812         free_xid(xid);
2813
2814         cifs_dbg(FYI, "%s: rc = %d ACL len %d\n", __func__, rc, *pacllen);
2815         if (rc)
2816                 return ERR_PTR(rc);
2817         return pntsd;
2818 }
2819
2820 static int
2821 set_smb2_acl(struct cifs_ntsd *pnntsd, __u32 acllen,
2822                 struct inode *inode, const char *path, int aclflag)
2823 {
2824         u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
2825         unsigned int xid;
2826         int rc, access_flags = 0;
2827         struct cifs_tcon *tcon;
2828         struct cifs_sb_info *cifs_sb = CIFS_SB(inode->i_sb);
2829         struct tcon_link *tlink = cifs_sb_tlink(cifs_sb);
2830         struct cifs_fid fid;
2831         struct cifs_open_parms oparms;
2832         __le16 *utf16_path;
2833
2834         cifs_dbg(FYI, "set smb3 acl for path %s\n", path);
2835         if (IS_ERR(tlink))
2836                 return PTR_ERR(tlink);
2837
2838         tcon = tlink_tcon(tlink);
2839         xid = get_xid();
2840
2841         if (backup_cred(cifs_sb))
2842                 oparms.create_options = CREATE_OPEN_BACKUP_INTENT;
2843         else
2844                 oparms.create_options = 0;
2845
2846         if (aclflag == CIFS_ACL_OWNER || aclflag == CIFS_ACL_GROUP)
2847                 access_flags = WRITE_OWNER;
2848         else
2849                 access_flags = WRITE_DAC;
2850
2851         utf16_path = cifs_convert_path_to_utf16(path, cifs_sb);
2852         if (!utf16_path) {
2853                 rc = -ENOMEM;
2854                 free_xid(xid);
2855                 return rc;
2856         }
2857
2858         oparms.tcon = tcon;
2859         oparms.desired_access = access_flags;
2860         oparms.disposition = FILE_OPEN;
2861         oparms.path = path;
2862         oparms.fid = &fid;
2863         oparms.reconnect = false;
2864
2865         rc = SMB2_open(xid, &oparms, utf16_path, &oplock, NULL, NULL, NULL);
2866         kfree(utf16_path);
2867         if (!rc) {
2868                 rc = SMB2_set_acl(xid, tlink_tcon(tlink), fid.persistent_fid,
2869                             fid.volatile_fid, pnntsd, acllen, aclflag);
2870                 SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
2871         }
2872
2873         cifs_put_tlink(tlink);
2874         free_xid(xid);
2875         return rc;
2876 }
2877
2878 /* Retrieve an ACL from the server */
2879 static struct cifs_ntsd *
2880 get_smb2_acl(struct cifs_sb_info *cifs_sb,
2881                                       struct inode *inode, const char *path,
2882                                       u32 *pacllen)
2883 {
2884         struct cifs_ntsd *pntsd = NULL;
2885         struct cifsFileInfo *open_file = NULL;
2886
2887         if (inode)
2888                 open_file = find_readable_file(CIFS_I(inode), true);
2889         if (!open_file)
2890                 return get_smb2_acl_by_path(cifs_sb, path, pacllen);
2891
2892         pntsd = get_smb2_acl_by_fid(cifs_sb, &open_file->fid, pacllen);
2893         cifsFileInfo_put(open_file);
2894         return pntsd;
2895 }
2896
2897 static long smb3_zero_range(struct file *file, struct cifs_tcon *tcon,
2898                             loff_t offset, loff_t len, bool keep_size)
2899 {
2900         struct cifs_ses *ses = tcon->ses;
2901         struct inode *inode;
2902         struct cifsInodeInfo *cifsi;
2903         struct cifsFileInfo *cfile = file->private_data;
2904         struct file_zero_data_information fsctl_buf;
2905         long rc;
2906         unsigned int xid;
2907         __le64 eof;
2908
2909         xid = get_xid();
2910
2911         inode = d_inode(cfile->dentry);
2912         cifsi = CIFS_I(inode);
2913
2914         trace_smb3_zero_enter(xid, cfile->fid.persistent_fid, tcon->tid,
2915                               ses->Suid, offset, len);
2916
2917
2918         /* if file not oplocked can't be sure whether asking to extend size */
2919         if (!CIFS_CACHE_READ(cifsi))
2920                 if (keep_size == false) {
2921                         rc = -EOPNOTSUPP;
2922                         trace_smb3_zero_err(xid, cfile->fid.persistent_fid,
2923                                 tcon->tid, ses->Suid, offset, len, rc);
2924                         free_xid(xid);
2925                         return rc;
2926                 }
2927
2928         cifs_dbg(FYI, "Offset %lld len %lld\n", offset, len);
2929
2930         fsctl_buf.FileOffset = cpu_to_le64(offset);
2931         fsctl_buf.BeyondFinalZero = cpu_to_le64(offset + len);
2932
2933         rc = SMB2_ioctl(xid, tcon, cfile->fid.persistent_fid,
2934                         cfile->fid.volatile_fid, FSCTL_SET_ZERO_DATA, true,
2935                         (char *)&fsctl_buf,
2936                         sizeof(struct file_zero_data_information),
2937                         0, NULL, NULL);
2938         if (rc)
2939                 goto zero_range_exit;
2940
2941         /*
2942          * do we also need to change the size of the file?
2943          */
2944         if (keep_size == false && i_size_read(inode) < offset + len) {
2945                 eof = cpu_to_le64(offset + len);
2946                 rc = SMB2_set_eof(xid, tcon, cfile->fid.persistent_fid,
2947                                   cfile->fid.volatile_fid, cfile->pid, &eof);
2948         }
2949
2950  zero_range_exit:
2951         free_xid(xid);
2952         if (rc)
2953                 trace_smb3_zero_err(xid, cfile->fid.persistent_fid, tcon->tid,
2954                               ses->Suid, offset, len, rc);
2955         else
2956                 trace_smb3_zero_done(xid, cfile->fid.persistent_fid, tcon->tid,
2957                               ses->Suid, offset, len);
2958         return rc;
2959 }
2960
2961 static long smb3_punch_hole(struct file *file, struct cifs_tcon *tcon,
2962                             loff_t offset, loff_t len)
2963 {
2964         struct inode *inode;
2965         struct cifsFileInfo *cfile = file->private_data;
2966         struct file_zero_data_information fsctl_buf;
2967         long rc;
2968         unsigned int xid;
2969         __u8 set_sparse = 1;
2970
2971         xid = get_xid();
2972
2973         inode = d_inode(cfile->dentry);
2974
2975         /* Need to make file sparse, if not already, before freeing range. */
2976         /* Consider adding equivalent for compressed since it could also work */
2977         if (!smb2_set_sparse(xid, tcon, cfile, inode, set_sparse)) {
2978                 rc = -EOPNOTSUPP;
2979                 free_xid(xid);
2980                 return rc;
2981         }
2982
2983         cifs_dbg(FYI, "Offset %lld len %lld\n", offset, len);
2984
2985         fsctl_buf.FileOffset = cpu_to_le64(offset);
2986         fsctl_buf.BeyondFinalZero = cpu_to_le64(offset + len);
2987
2988         rc = SMB2_ioctl(xid, tcon, cfile->fid.persistent_fid,
2989                         cfile->fid.volatile_fid, FSCTL_SET_ZERO_DATA,
2990                         true /* is_fctl */, (char *)&fsctl_buf,
2991                         sizeof(struct file_zero_data_information),
2992                         CIFSMaxBufSize, NULL, NULL);
2993         free_xid(xid);
2994         return rc;
2995 }
2996
2997 static long smb3_simple_falloc(struct file *file, struct cifs_tcon *tcon,
2998                             loff_t off, loff_t len, bool keep_size)
2999 {
3000         struct inode *inode;
3001         struct cifsInodeInfo *cifsi;
3002         struct cifsFileInfo *cfile = file->private_data;
3003         long rc = -EOPNOTSUPP;
3004         unsigned int xid;
3005         __le64 eof;
3006
3007         xid = get_xid();
3008
3009         inode = d_inode(cfile->dentry);
3010         cifsi = CIFS_I(inode);
3011
3012         trace_smb3_falloc_enter(xid, cfile->fid.persistent_fid, tcon->tid,
3013                                 tcon->ses->Suid, off, len);
3014         /* if file not oplocked can't be sure whether asking to extend size */
3015         if (!CIFS_CACHE_READ(cifsi))
3016                 if (keep_size == false) {
3017                         trace_smb3_falloc_err(xid, cfile->fid.persistent_fid,
3018                                 tcon->tid, tcon->ses->Suid, off, len, rc);
3019                         free_xid(xid);
3020                         return rc;
3021                 }
3022
3023         /*
3024          * Files are non-sparse by default so falloc may be a no-op
3025          * Must check if file sparse. If not sparse, and not extending
3026          * then no need to do anything since file already allocated
3027          */
3028         if ((cifsi->cifsAttrs & FILE_ATTRIBUTE_SPARSE_FILE) == 0) {
3029                 if (keep_size == true)
3030                         rc = 0;
3031                 /* check if extending file */
3032                 else if (i_size_read(inode) >= off + len)
3033                         /* not extending file and already not sparse */
3034                         rc = 0;
3035                 /* BB: in future add else clause to extend file */
3036                 else
3037                         rc = -EOPNOTSUPP;
3038                 if (rc)
3039                         trace_smb3_falloc_err(xid, cfile->fid.persistent_fid,
3040                                 tcon->tid, tcon->ses->Suid, off, len, rc);
3041                 else
3042                         trace_smb3_falloc_done(xid, cfile->fid.persistent_fid,
3043                                 tcon->tid, tcon->ses->Suid, off, len);
3044                 free_xid(xid);
3045                 return rc;
3046         }
3047
3048         if ((keep_size == true) || (i_size_read(inode) >= off + len)) {
3049                 /*
3050                  * Check if falloc starts within first few pages of file
3051                  * and ends within a few pages of the end of file to
3052                  * ensure that most of file is being forced to be
3053                  * fallocated now. If so then setting whole file sparse
3054                  * ie potentially making a few extra pages at the beginning
3055                  * or end of the file non-sparse via set_sparse is harmless.
3056                  */
3057                 if ((off > 8192) || (off + len + 8192 < i_size_read(inode))) {
3058                         rc = -EOPNOTSUPP;
3059                         trace_smb3_falloc_err(xid, cfile->fid.persistent_fid,
3060                                 tcon->tid, tcon->ses->Suid, off, len, rc);
3061                         free_xid(xid);
3062                         return rc;
3063                 }
3064
3065                 smb2_set_sparse(xid, tcon, cfile, inode, false);
3066                 rc = 0;
3067         } else {
3068                 smb2_set_sparse(xid, tcon, cfile, inode, false);
3069                 rc = 0;
3070                 if (i_size_read(inode) < off + len) {
3071                         eof = cpu_to_le64(off + len);
3072                         rc = SMB2_set_eof(xid, tcon, cfile->fid.persistent_fid,
3073                                           cfile->fid.volatile_fid, cfile->pid,
3074                                           &eof);
3075                 }
3076         }
3077
3078         if (rc)
3079                 trace_smb3_falloc_err(xid, cfile->fid.persistent_fid, tcon->tid,
3080                                 tcon->ses->Suid, off, len, rc);
3081         else
3082                 trace_smb3_falloc_done(xid, cfile->fid.persistent_fid, tcon->tid,
3083                                 tcon->ses->Suid, off, len);
3084
3085         free_xid(xid);
3086         return rc;
3087 }
3088
3089 static loff_t smb3_llseek(struct file *file, struct cifs_tcon *tcon, loff_t offset, int whence)
3090 {
3091         struct cifsFileInfo *wrcfile, *cfile = file->private_data;
3092         struct cifsInodeInfo *cifsi;
3093         struct inode *inode;
3094         int rc = 0;
3095         struct file_allocated_range_buffer in_data, *out_data = NULL;
3096         u32 out_data_len;
3097         unsigned int xid;
3098
3099         if (whence != SEEK_HOLE && whence != SEEK_DATA)
3100                 return generic_file_llseek(file, offset, whence);
3101
3102         inode = d_inode(cfile->dentry);
3103         cifsi = CIFS_I(inode);
3104
3105         if (offset < 0 || offset >= i_size_read(inode))
3106                 return -ENXIO;
3107
3108         xid = get_xid();
3109         /*
3110          * We need to be sure that all dirty pages are written as they
3111          * might fill holes on the server.
3112          * Note that we also MUST flush any written pages since at least
3113          * some servers (Windows2016) will not reflect recent writes in
3114          * QUERY_ALLOCATED_RANGES until SMB2_flush is called.
3115          */
3116         wrcfile = find_writable_file(cifsi, false);
3117         if (wrcfile) {
3118                 filemap_write_and_wait(inode->i_mapping);
3119                 smb2_flush_file(xid, tcon, &wrcfile->fid);
3120                 cifsFileInfo_put(wrcfile);
3121         }
3122
3123         if (!(cifsi->cifsAttrs & FILE_ATTRIBUTE_SPARSE_FILE)) {
3124                 if (whence == SEEK_HOLE)
3125                         offset = i_size_read(inode);
3126                 goto lseek_exit;
3127         }
3128
3129         in_data.file_offset = cpu_to_le64(offset);
3130         in_data.length = cpu_to_le64(i_size_read(inode));
3131
3132         rc = SMB2_ioctl(xid, tcon, cfile->fid.persistent_fid,
3133                         cfile->fid.volatile_fid,
3134                         FSCTL_QUERY_ALLOCATED_RANGES, true,
3135                         (char *)&in_data, sizeof(in_data),
3136                         sizeof(struct file_allocated_range_buffer),
3137                         (char **)&out_data, &out_data_len);
3138         if (rc == -E2BIG)
3139                 rc = 0;
3140         if (rc)
3141                 goto lseek_exit;
3142
3143         if (whence == SEEK_HOLE && out_data_len == 0)
3144                 goto lseek_exit;
3145
3146         if (whence == SEEK_DATA && out_data_len == 0) {
3147                 rc = -ENXIO;
3148                 goto lseek_exit;
3149         }
3150
3151         if (out_data_len < sizeof(struct file_allocated_range_buffer)) {
3152                 rc = -EINVAL;
3153                 goto lseek_exit;
3154         }
3155         if (whence == SEEK_DATA) {
3156                 offset = le64_to_cpu(out_data->file_offset);
3157                 goto lseek_exit;
3158         }
3159         if (offset < le64_to_cpu(out_data->file_offset))
3160                 goto lseek_exit;
3161
3162         offset = le64_to_cpu(out_data->file_offset) + le64_to_cpu(out_data->length);
3163
3164  lseek_exit:
3165         free_xid(xid);
3166         kfree(out_data);
3167         if (!rc)
3168                 return vfs_setpos(file, offset, inode->i_sb->s_maxbytes);
3169         else
3170                 return rc;
3171 }
3172
3173 static int smb3_fiemap(struct cifs_tcon *tcon,
3174                        struct cifsFileInfo *cfile,
3175                        struct fiemap_extent_info *fei, u64 start, u64 len)
3176 {
3177         unsigned int xid;
3178         struct file_allocated_range_buffer in_data, *out_data;
3179         u32 out_data_len;
3180         int i, num, rc, flags, last_blob;
3181         u64 next;
3182
3183         if (fiemap_check_flags(fei, FIEMAP_FLAG_SYNC))
3184                 return -EBADR;
3185
3186         xid = get_xid();
3187  again:
3188         in_data.file_offset = cpu_to_le64(start);
3189         in_data.length = cpu_to_le64(len);
3190
3191         rc = SMB2_ioctl(xid, tcon, cfile->fid.persistent_fid,
3192                         cfile->fid.volatile_fid,
3193                         FSCTL_QUERY_ALLOCATED_RANGES, true,
3194                         (char *)&in_data, sizeof(in_data),
3195                         1024 * sizeof(struct file_allocated_range_buffer),
3196                         (char **)&out_data, &out_data_len);
3197         if (rc == -E2BIG) {
3198                 last_blob = 0;
3199                 rc = 0;
3200         } else
3201                 last_blob = 1;
3202         if (rc)
3203                 goto out;
3204
3205         if (out_data_len < sizeof(struct file_allocated_range_buffer)) {
3206                 rc = -EINVAL;
3207                 goto out;
3208         }
3209         if (out_data_len % sizeof(struct file_allocated_range_buffer)) {
3210                 rc = -EINVAL;
3211                 goto out;
3212         }
3213
3214         num = out_data_len / sizeof(struct file_allocated_range_buffer);
3215         for (i = 0; i < num; i++) {
3216                 flags = 0;
3217                 if (i == num - 1 && last_blob)
3218                         flags |= FIEMAP_EXTENT_LAST;
3219
3220                 rc = fiemap_fill_next_extent(fei,
3221                                 le64_to_cpu(out_data[i].file_offset),
3222                                 le64_to_cpu(out_data[i].file_offset),
3223                                 le64_to_cpu(out_data[i].length),
3224                                 flags);
3225                 if (rc < 0)
3226                         goto out;
3227                 if (rc == 1) {
3228                         rc = 0;
3229                         goto out;
3230                 }
3231         }
3232
3233         if (!last_blob) {
3234                 next = le64_to_cpu(out_data[num - 1].file_offset) +
3235                   le64_to_cpu(out_data[num - 1].length);
3236                 len = len - (next - start);
3237                 start = next;
3238                 goto again;
3239         }
3240
3241  out:
3242         free_xid(xid);
3243         kfree(out_data);
3244         return rc;
3245 }
3246
3247 static long smb3_fallocate(struct file *file, struct cifs_tcon *tcon, int mode,
3248                            loff_t off, loff_t len)
3249 {
3250         /* KEEP_SIZE already checked for by do_fallocate */
3251         if (mode & FALLOC_FL_PUNCH_HOLE)
3252                 return smb3_punch_hole(file, tcon, off, len);
3253         else if (mode & FALLOC_FL_ZERO_RANGE) {
3254                 if (mode & FALLOC_FL_KEEP_SIZE)
3255                         return smb3_zero_range(file, tcon, off, len, true);
3256                 return smb3_zero_range(file, tcon, off, len, false);
3257         } else if (mode == FALLOC_FL_KEEP_SIZE)
3258                 return smb3_simple_falloc(file, tcon, off, len, true);
3259         else if (mode == 0)
3260                 return smb3_simple_falloc(file, tcon, off, len, false);
3261
3262         return -EOPNOTSUPP;
3263 }
3264
3265 static void
3266 smb2_downgrade_oplock(struct TCP_Server_Info *server,
3267                         struct cifsInodeInfo *cinode, bool set_level2)
3268 {
3269         if (set_level2)
3270                 server->ops->set_oplock_level(cinode, SMB2_OPLOCK_LEVEL_II,
3271                                                 0, NULL);
3272         else
3273                 server->ops->set_oplock_level(cinode, 0, 0, NULL);
3274 }
3275
3276 static void
3277 smb21_downgrade_oplock(struct TCP_Server_Info *server,
3278                        struct cifsInodeInfo *cinode, bool set_level2)
3279 {
3280         server->ops->set_oplock_level(cinode,
3281                                       set_level2 ? SMB2_LEASE_READ_CACHING_HE :
3282                                       0, 0, NULL);
3283 }
3284
3285 static void
3286 smb2_set_oplock_level(struct cifsInodeInfo *cinode, __u32 oplock,
3287                       unsigned int epoch, bool *purge_cache)
3288 {
3289         oplock &= 0xFF;
3290         if (oplock == SMB2_OPLOCK_LEVEL_NOCHANGE)
3291                 return;
3292         if (oplock == SMB2_OPLOCK_LEVEL_BATCH) {
3293                 cinode->oplock = CIFS_CACHE_RHW_FLG;
3294                 cifs_dbg(FYI, "Batch Oplock granted on inode %p\n",
3295                          &cinode->vfs_inode);
3296         } else if (oplock == SMB2_OPLOCK_LEVEL_EXCLUSIVE) {
3297                 cinode->oplock = CIFS_CACHE_RW_FLG;
3298                 cifs_dbg(FYI, "Exclusive Oplock granted on inode %p\n",
3299                          &cinode->vfs_inode);
3300         } else if (oplock == SMB2_OPLOCK_LEVEL_II) {
3301                 cinode->oplock = CIFS_CACHE_READ_FLG;
3302                 cifs_dbg(FYI, "Level II Oplock granted on inode %p\n",
3303                          &cinode->vfs_inode);
3304         } else
3305                 cinode->oplock = 0;
3306 }
3307
3308 static void
3309 smb21_set_oplock_level(struct cifsInodeInfo *cinode, __u32 oplock,
3310                        unsigned int epoch, bool *purge_cache)
3311 {
3312         char message[5] = {0};
3313         unsigned int new_oplock = 0;
3314
3315         oplock &= 0xFF;
3316         if (oplock == SMB2_OPLOCK_LEVEL_NOCHANGE)
3317                 return;
3318
3319         if (oplock & SMB2_LEASE_READ_CACHING_HE) {
3320                 new_oplock |= CIFS_CACHE_READ_FLG;
3321                 strcat(message, "R");
3322         }
3323         if (oplock & SMB2_LEASE_HANDLE_CACHING_HE) {
3324                 new_oplock |= CIFS_CACHE_HANDLE_FLG;
3325                 strcat(message, "H");
3326         }
3327         if (oplock & SMB2_LEASE_WRITE_CACHING_HE) {
3328                 new_oplock |= CIFS_CACHE_WRITE_FLG;
3329                 strcat(message, "W");
3330         }
3331         if (!new_oplock)
3332                 strncpy(message, "None", sizeof(message));
3333
3334         cinode->oplock = new_oplock;
3335         cifs_dbg(FYI, "%s Lease granted on inode %p\n", message,
3336                  &cinode->vfs_inode);
3337 }
3338
3339 static void
3340 smb3_set_oplock_level(struct cifsInodeInfo *cinode, __u32 oplock,
3341                       unsigned int epoch, bool *purge_cache)
3342 {
3343         unsigned int old_oplock = cinode->oplock;
3344
3345         smb21_set_oplock_level(cinode, oplock, epoch, purge_cache);
3346
3347         if (purge_cache) {
3348                 *purge_cache = false;
3349                 if (old_oplock == CIFS_CACHE_READ_FLG) {
3350                         if (cinode->oplock == CIFS_CACHE_READ_FLG &&
3351                             (epoch - cinode->epoch > 0))
3352                                 *purge_cache = true;
3353                         else if (cinode->oplock == CIFS_CACHE_RH_FLG &&
3354                                  (epoch - cinode->epoch > 1))
3355                                 *purge_cache = true;
3356                         else if (cinode->oplock == CIFS_CACHE_RHW_FLG &&
3357                                  (epoch - cinode->epoch > 1))
3358                                 *purge_cache = true;
3359                         else if (cinode->oplock == 0 &&
3360                                  (epoch - cinode->epoch > 0))
3361                                 *purge_cache = true;
3362                 } else if (old_oplock == CIFS_CACHE_RH_FLG) {
3363                         if (cinode->oplock == CIFS_CACHE_RH_FLG &&
3364                             (epoch - cinode->epoch > 0))
3365                                 *purge_cache = true;
3366                         else if (cinode->oplock == CIFS_CACHE_RHW_FLG &&
3367                                  (epoch - cinode->epoch > 1))
3368                                 *purge_cache = true;
3369                 }
3370                 cinode->epoch = epoch;
3371         }
3372 }
3373
3374 static bool
3375 smb2_is_read_op(__u32 oplock)
3376 {
3377         return oplock == SMB2_OPLOCK_LEVEL_II;
3378 }
3379
3380 static bool
3381 smb21_is_read_op(__u32 oplock)
3382 {
3383         return (oplock & SMB2_LEASE_READ_CACHING_HE) &&
3384                !(oplock & SMB2_LEASE_WRITE_CACHING_HE);
3385 }
3386
3387 static __le32
3388 map_oplock_to_lease(u8 oplock)
3389 {
3390         if (oplock == SMB2_OPLOCK_LEVEL_EXCLUSIVE)
3391                 return SMB2_LEASE_WRITE_CACHING | SMB2_LEASE_READ_CACHING;
3392         else if (oplock == SMB2_OPLOCK_LEVEL_II)
3393                 return SMB2_LEASE_READ_CACHING;
3394         else if (oplock == SMB2_OPLOCK_LEVEL_BATCH)
3395                 return SMB2_LEASE_HANDLE_CACHING | SMB2_LEASE_READ_CACHING |
3396                        SMB2_LEASE_WRITE_CACHING;
3397         return 0;
3398 }
3399
3400 static char *
3401 smb2_create_lease_buf(u8 *lease_key, u8 oplock)
3402 {
3403         struct create_lease *buf;
3404
3405         buf = kzalloc(sizeof(struct create_lease), GFP_KERNEL);
3406         if (!buf)
3407                 return NULL;
3408
3409         memcpy(&buf->lcontext.LeaseKey, lease_key, SMB2_LEASE_KEY_SIZE);
3410         buf->lcontext.LeaseState = map_oplock_to_lease(oplock);
3411
3412         buf->ccontext.DataOffset = cpu_to_le16(offsetof
3413                                         (struct create_lease, lcontext));
3414         buf->ccontext.DataLength = cpu_to_le32(sizeof(struct lease_context));
3415         buf->ccontext.NameOffset = cpu_to_le16(offsetof
3416                                 (struct create_lease, Name));
3417         buf->ccontext.NameLength = cpu_to_le16(4);
3418         /* SMB2_CREATE_REQUEST_LEASE is "RqLs" */
3419         buf->Name[0] = 'R';
3420         buf->Name[1] = 'q';
3421         buf->Name[2] = 'L';
3422         buf->Name[3] = 's';
3423         return (char *)buf;
3424 }
3425
3426 static char *
3427 smb3_create_lease_buf(u8 *lease_key, u8 oplock)
3428 {
3429         struct create_lease_v2 *buf;
3430
3431         buf = kzalloc(sizeof(struct create_lease_v2), GFP_KERNEL);
3432         if (!buf)
3433                 return NULL;
3434
3435         memcpy(&buf->lcontext.LeaseKey, lease_key, SMB2_LEASE_KEY_SIZE);
3436         buf->lcontext.LeaseState = map_oplock_to_lease(oplock);
3437
3438         buf->ccontext.DataOffset = cpu_to_le16(offsetof
3439                                         (struct create_lease_v2, lcontext));
3440         buf->ccontext.DataLength = cpu_to_le32(sizeof(struct lease_context_v2));
3441         buf->ccontext.NameOffset = cpu_to_le16(offsetof
3442                                 (struct create_lease_v2, Name));
3443         buf->ccontext.NameLength = cpu_to_le16(4);
3444         /* SMB2_CREATE_REQUEST_LEASE is "RqLs" */
3445         buf->Name[0] = 'R';
3446         buf->Name[1] = 'q';
3447         buf->Name[2] = 'L';
3448         buf->Name[3] = 's';
3449         return (char *)buf;
3450 }
3451
3452 static __u8
3453 smb2_parse_lease_buf(void *buf, unsigned int *epoch, char *lease_key)
3454 {
3455         struct create_lease *lc = (struct create_lease *)buf;
3456
3457         *epoch = 0; /* not used */
3458         if (lc->lcontext.LeaseFlags & SMB2_LEASE_FLAG_BREAK_IN_PROGRESS)
3459                 return SMB2_OPLOCK_LEVEL_NOCHANGE;
3460         return le32_to_cpu(lc->lcontext.LeaseState);
3461 }
3462
3463 static __u8
3464 smb3_parse_lease_buf(void *buf, unsigned int *epoch, char *lease_key)
3465 {
3466         struct create_lease_v2 *lc = (struct create_lease_v2 *)buf;
3467
3468         *epoch = le16_to_cpu(lc->lcontext.Epoch);
3469         if (lc->lcontext.LeaseFlags & SMB2_LEASE_FLAG_BREAK_IN_PROGRESS)
3470                 return SMB2_OPLOCK_LEVEL_NOCHANGE;
3471         if (lease_key)
3472                 memcpy(lease_key, &lc->lcontext.LeaseKey, SMB2_LEASE_KEY_SIZE);
3473         return le32_to_cpu(lc->lcontext.LeaseState);
3474 }
3475
3476 static unsigned int
3477 smb2_wp_retry_size(struct inode *inode)
3478 {
3479         return min_t(unsigned int, CIFS_SB(inode->i_sb)->wsize,
3480                      SMB2_MAX_BUFFER_SIZE);
3481 }
3482
3483 static bool
3484 smb2_dir_needs_close(struct cifsFileInfo *cfile)
3485 {
3486         return !cfile->invalidHandle;
3487 }
3488
3489 static void
3490 fill_transform_hdr(struct smb2_transform_hdr *tr_hdr, unsigned int orig_len,
3491                    struct smb_rqst *old_rq, __le16 cipher_type)
3492 {
3493         struct smb2_sync_hdr *shdr =
3494                         (struct smb2_sync_hdr *)old_rq->rq_iov[0].iov_base;
3495
3496         memset(tr_hdr, 0, sizeof(struct smb2_transform_hdr));
3497         tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
3498         tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
3499         tr_hdr->Flags = cpu_to_le16(0x01);
3500         if (cipher_type == SMB2_ENCRYPTION_AES128_GCM)
3501                 get_random_bytes(&tr_hdr->Nonce, SMB3_AES128GCM_NONCE);
3502         else
3503                 get_random_bytes(&tr_hdr->Nonce, SMB3_AES128CCM_NONCE);
3504         memcpy(&tr_hdr->SessionId, &shdr->SessionId, 8);
3505 }
3506
3507 /* We can not use the normal sg_set_buf() as we will sometimes pass a
3508  * stack object as buf.
3509  */
3510 static inline void smb2_sg_set_buf(struct scatterlist *sg, const void *buf,
3511                                    unsigned int buflen)
3512 {
3513         void *addr;
3514         /*
3515          * VMAP_STACK (at least) puts stack into the vmalloc address space
3516          */
3517         if (is_vmalloc_addr(buf))
3518                 addr = vmalloc_to_page(buf);
3519         else
3520                 addr = virt_to_page(buf);
3521         sg_set_page(sg, addr, buflen, offset_in_page(buf));
3522 }
3523
3524 /* Assumes the first rqst has a transform header as the first iov.
3525  * I.e.
3526  * rqst[0].rq_iov[0]  is transform header
3527  * rqst[0].rq_iov[1+] data to be encrypted/decrypted
3528  * rqst[1+].rq_iov[0+] data to be encrypted/decrypted
3529  */
3530 static struct scatterlist *
3531 init_sg(int num_rqst, struct smb_rqst *rqst, u8 *sign)
3532 {
3533         unsigned int sg_len;
3534         struct scatterlist *sg;
3535         unsigned int i;
3536         unsigned int j;
3537         unsigned int idx = 0;
3538         int skip;
3539
3540         sg_len = 1;
3541         for (i = 0; i < num_rqst; i++)
3542                 sg_len += rqst[i].rq_nvec + rqst[i].rq_npages;
3543
3544         sg = kmalloc_array(sg_len, sizeof(struct scatterlist), GFP_KERNEL);
3545         if (!sg)
3546                 return NULL;
3547
3548         sg_init_table(sg, sg_len);
3549         for (i = 0; i < num_rqst; i++) {
3550                 for (j = 0; j < rqst[i].rq_nvec; j++) {
3551                         /*
3552                          * The first rqst has a transform header where the
3553                          * first 20 bytes are not part of the encrypted blob
3554                          */
3555                         skip = (i == 0) && (j == 0) ? 20 : 0;
3556                         smb2_sg_set_buf(&sg[idx++],
3557                                         rqst[i].rq_iov[j].iov_base + skip,
3558                                         rqst[i].rq_iov[j].iov_len - skip);
3559                         }
3560
3561                 for (j = 0; j < rqst[i].rq_npages; j++) {
3562                         unsigned int len, offset;
3563
3564                         rqst_page_get_length(&rqst[i], j, &len, &offset);
3565                         sg_set_page(&sg[idx++], rqst[i].rq_pages[j], len, offset);
3566                 }
3567         }
3568         smb2_sg_set_buf(&sg[idx], sign, SMB2_SIGNATURE_SIZE);
3569         return sg;
3570 }
3571
3572 static int
3573 smb2_get_enc_key(struct TCP_Server_Info *server, __u64 ses_id, int enc, u8 *key)
3574 {
3575         struct cifs_ses *ses;
3576         u8 *ses_enc_key;
3577
3578         spin_lock(&cifs_tcp_ses_lock);
3579         list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {
3580                 if (ses->Suid != ses_id)
3581                         continue;
3582                 ses_enc_key = enc ? ses->smb3encryptionkey :
3583                                                         ses->smb3decryptionkey;
3584                 memcpy(key, ses_enc_key, SMB3_SIGN_KEY_SIZE);
3585                 spin_unlock(&cifs_tcp_ses_lock);
3586                 return 0;
3587         }
3588         spin_unlock(&cifs_tcp_ses_lock);
3589
3590         return 1;
3591 }
3592 /*
3593  * Encrypt or decrypt @rqst message. @rqst[0] has the following format:
3594  * iov[0]   - transform header (associate data),
3595  * iov[1-N] - SMB2 header and pages - data to encrypt.
3596  * On success return encrypted data in iov[1-N] and pages, leave iov[0]
3597  * untouched.
3598  */
3599 static int
3600 crypt_message(struct TCP_Server_Info *server, int num_rqst,
3601               struct smb_rqst *rqst, int enc)
3602 {
3603         struct smb2_transform_hdr *tr_hdr =
3604                 (struct smb2_transform_hdr *)rqst[0].rq_iov[0].iov_base;
3605         unsigned int assoc_data_len = sizeof(struct smb2_transform_hdr) - 20;
3606         int rc = 0;
3607         struct scatterlist *sg;
3608         u8 sign[SMB2_SIGNATURE_SIZE] = {};
3609         u8 key[SMB3_SIGN_KEY_SIZE];
3610         struct aead_request *req;
3611         char *iv;
3612         unsigned int iv_len;
3613         DECLARE_CRYPTO_WAIT(wait);
3614         struct crypto_aead *tfm;
3615         unsigned int crypt_len = le32_to_cpu(tr_hdr->OriginalMessageSize);
3616
3617         rc = smb2_get_enc_key(server, tr_hdr->SessionId, enc, key);
3618         if (rc) {
3619                 cifs_server_dbg(VFS, "%s: Could not get %scryption key\n", __func__,
3620                          enc ? "en" : "de");
3621                 return 0;
3622         }
3623
3624         rc = smb3_crypto_aead_allocate(server);
3625         if (rc) {
3626                 cifs_server_dbg(VFS, "%s: crypto alloc failed\n", __func__);
3627                 return rc;
3628         }
3629
3630         tfm = enc ? server->secmech.ccmaesencrypt :
3631                                                 server->secmech.ccmaesdecrypt;
3632         rc = crypto_aead_setkey(tfm, key, SMB3_SIGN_KEY_SIZE);
3633         if (rc) {
3634                 cifs_server_dbg(VFS, "%s: Failed to set aead key %d\n", __func__, rc);
3635                 return rc;
3636         }
3637
3638         rc = crypto_aead_setauthsize(tfm, SMB2_SIGNATURE_SIZE);
3639         if (rc) {
3640                 cifs_server_dbg(VFS, "%s: Failed to set authsize %d\n", __func__, rc);
3641                 return rc;
3642         }
3643
3644         req = aead_request_alloc(tfm, GFP_KERNEL);
3645         if (!req) {
3646                 cifs_server_dbg(VFS, "%s: Failed to alloc aead request\n", __func__);
3647                 return -ENOMEM;
3648         }
3649
3650         if (!enc) {
3651                 memcpy(sign, &tr_hdr->Signature, SMB2_SIGNATURE_SIZE);
3652                 crypt_len += SMB2_SIGNATURE_SIZE;
3653         }
3654
3655         sg = init_sg(num_rqst, rqst, sign);
3656         if (!sg) {
3657                 cifs_server_dbg(VFS, "%s: Failed to init sg\n", __func__);
3658                 rc = -ENOMEM;
3659                 goto free_req;
3660         }
3661
3662         iv_len = crypto_aead_ivsize(tfm);
3663         iv = kzalloc(iv_len, GFP_KERNEL);
3664         if (!iv) {
3665                 cifs_server_dbg(VFS, "%s: Failed to alloc iv\n", __func__);
3666                 rc = -ENOMEM;
3667                 goto free_sg;
3668         }
3669
3670         if (server->cipher_type == SMB2_ENCRYPTION_AES128_GCM)
3671                 memcpy(iv, (char *)tr_hdr->Nonce, SMB3_AES128GCM_NONCE);
3672         else {
3673                 iv[0] = 3;
3674                 memcpy(iv + 1, (char *)tr_hdr->Nonce, SMB3_AES128CCM_NONCE);
3675         }
3676
3677         aead_request_set_crypt(req, sg, sg, crypt_len, iv);
3678         aead_request_set_ad(req, assoc_data_len);
3679
3680         aead_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
3681                                   crypto_req_done, &wait);
3682
3683         rc = crypto_wait_req(enc ? crypto_aead_encrypt(req)
3684                                 : crypto_aead_decrypt(req), &wait);
3685
3686         if (!rc && enc)
3687                 memcpy(&tr_hdr->Signature, sign, SMB2_SIGNATURE_SIZE);
3688
3689         kfree(iv);
3690 free_sg:
3691         kfree(sg);
3692 free_req:
3693         kfree(req);
3694         return rc;
3695 }
3696
3697 void
3698 smb3_free_compound_rqst(int num_rqst, struct smb_rqst *rqst)
3699 {
3700         int i, j;
3701
3702         for (i = 0; i < num_rqst; i++) {
3703                 if (rqst[i].rq_pages) {
3704                         for (j = rqst[i].rq_npages - 1; j >= 0; j--)
3705                                 put_page(rqst[i].rq_pages[j]);
3706                         kfree(rqst[i].rq_pages);
3707                 }
3708         }
3709 }
3710
3711 /*
3712  * This function will initialize new_rq and encrypt the content.
3713  * The first entry, new_rq[0], only contains a single iov which contains
3714  * a smb2_transform_hdr and is pre-allocated by the caller.
3715  * This function then populates new_rq[1+] with the content from olq_rq[0+].
3716  *
3717  * The end result is an array of smb_rqst structures where the first structure
3718  * only contains a single iov for the transform header which we then can pass
3719  * to crypt_message().
3720  *
3721  * new_rq[0].rq_iov[0] :  smb2_transform_hdr pre-allocated by the caller
3722  * new_rq[1+].rq_iov[*] == old_rq[0+].rq_iov[*] : SMB2/3 requests
3723  */
3724 static int
3725 smb3_init_transform_rq(struct TCP_Server_Info *server, int num_rqst,
3726                        struct smb_rqst *new_rq, struct smb_rqst *old_rq)
3727 {
3728         struct page **pages;
3729         struct smb2_transform_hdr *tr_hdr = new_rq[0].rq_iov[0].iov_base;
3730         unsigned int npages;
3731         unsigned int orig_len = 0;
3732         int i, j;
3733         int rc = -ENOMEM;
3734
3735         for (i = 1; i < num_rqst; i++) {
3736                 npages = old_rq[i - 1].rq_npages;
3737                 pages = kmalloc_array(npages, sizeof(struct page *),
3738                                       GFP_KERNEL);
3739                 if (!pages)
3740                         goto err_free;
3741
3742                 new_rq[i].rq_pages = pages;
3743                 new_rq[i].rq_npages = npages;
3744                 new_rq[i].rq_offset = old_rq[i - 1].rq_offset;
3745                 new_rq[i].rq_pagesz = old_rq[i - 1].rq_pagesz;
3746                 new_rq[i].rq_tailsz = old_rq[i - 1].rq_tailsz;
3747                 new_rq[i].rq_iov = old_rq[i - 1].rq_iov;
3748                 new_rq[i].rq_nvec = old_rq[i - 1].rq_nvec;
3749
3750                 orig_len += smb_rqst_len(server, &old_rq[i - 1]);
3751
3752                 for (j = 0; j < npages; j++) {
3753                         pages[j] = alloc_page(GFP_KERNEL|__GFP_HIGHMEM);
3754                         if (!pages[j])
3755                                 goto err_free;
3756                 }
3757
3758                 /* copy pages form the old */
3759                 for (j = 0; j < npages; j++) {
3760                         char *dst, *src;
3761                         unsigned int offset, len;
3762
3763                         rqst_page_get_length(&new_rq[i], j, &len, &offset);
3764
3765                         dst = (char *) kmap(new_rq[i].rq_pages[j]) + offset;
3766                         src = (char *) kmap(old_rq[i - 1].rq_pages[j]) + offset;
3767
3768                         memcpy(dst, src, len);
3769                         kunmap(new_rq[i].rq_pages[j]);
3770                         kunmap(old_rq[i - 1].rq_pages[j]);
3771                 }
3772         }
3773
3774         /* fill the 1st iov with a transform header */
3775         fill_transform_hdr(tr_hdr, orig_len, old_rq, server->cipher_type);
3776
3777         rc = crypt_message(server, num_rqst, new_rq, 1);
3778         cifs_dbg(FYI, "Encrypt message returned %d\n", rc);
3779         if (rc)
3780                 goto err_free;
3781
3782         return rc;
3783
3784 err_free:
3785         smb3_free_compound_rqst(num_rqst - 1, &new_rq[1]);
3786         return rc;
3787 }
3788
3789 static int
3790 smb3_is_transform_hdr(void *buf)
3791 {
3792         struct smb2_transform_hdr *trhdr = buf;
3793
3794         return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
3795 }
3796
3797 static int
3798 decrypt_raw_data(struct TCP_Server_Info *server, char *buf,
3799                  unsigned int buf_data_size, struct page **pages,
3800                  unsigned int npages, unsigned int page_data_size)
3801 {
3802         struct kvec iov[2];
3803         struct smb_rqst rqst = {NULL};
3804         int rc;
3805
3806         iov[0].iov_base = buf;
3807         iov[0].iov_len = sizeof(struct smb2_transform_hdr);
3808         iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr);
3809         iov[1].iov_len = buf_data_size;
3810
3811         rqst.rq_iov = iov;
3812         rqst.rq_nvec = 2;
3813         rqst.rq_pages = pages;
3814         rqst.rq_npages = npages;
3815         rqst.rq_pagesz = PAGE_SIZE;
3816         rqst.rq_tailsz = (page_data_size % PAGE_SIZE) ? : PAGE_SIZE;
3817
3818         rc = crypt_message(server, 1, &rqst, 0);
3819         cifs_dbg(FYI, "Decrypt message returned %d\n", rc);
3820
3821         if (rc)
3822                 return rc;
3823
3824         memmove(buf, iov[1].iov_base, buf_data_size);
3825
3826         server->total_read = buf_data_size + page_data_size;
3827
3828         return rc;
3829 }
3830
3831 static int
3832 read_data_into_pages(struct TCP_Server_Info *server, struct page **pages,
3833                      unsigned int npages, unsigned int len)
3834 {
3835         int i;
3836         int length;
3837
3838         for (i = 0; i < npages; i++) {
3839                 struct page *page = pages[i];
3840                 size_t n;
3841
3842                 n = len;
3843                 if (len >= PAGE_SIZE) {
3844                         /* enough data to fill the page */
3845                         n = PAGE_SIZE;
3846                         len -= n;
3847                 } else {
3848                         zero_user(page, len, PAGE_SIZE - len);
3849                         len = 0;
3850                 }
3851                 length = cifs_read_page_from_socket(server, page, 0, n);
3852                 if (length < 0)
3853                         return length;
3854                 server->total_read += length;
3855         }
3856
3857         return 0;
3858 }
3859
3860 static int
3861 init_read_bvec(struct page **pages, unsigned int npages, unsigned int data_size,
3862                unsigned int cur_off, struct bio_vec **page_vec)
3863 {
3864         struct bio_vec *bvec;
3865         int i;
3866
3867         bvec = kcalloc(npages, sizeof(struct bio_vec), GFP_KERNEL);
3868         if (!bvec)
3869                 return -ENOMEM;
3870
3871         for (i = 0; i < npages; i++) {
3872                 bvec[i].bv_page = pages[i];
3873                 bvec[i].bv_offset = (i == 0) ? cur_off : 0;
3874                 bvec[i].bv_len = min_t(unsigned int, PAGE_SIZE, data_size);
3875                 data_size -= bvec[i].bv_len;
3876         }
3877
3878         if (data_size != 0) {
3879                 cifs_dbg(VFS, "%s: something went wrong\n", __func__);
3880                 kfree(bvec);
3881                 return -EIO;
3882         }
3883
3884         *page_vec = bvec;
3885         return 0;
3886 }
3887
3888 static int
3889 handle_read_data(struct TCP_Server_Info *server, struct mid_q_entry *mid,
3890                  char *buf, unsigned int buf_len, struct page **pages,
3891                  unsigned int npages, unsigned int page_data_size)
3892 {
3893         unsigned int data_offset;
3894         unsigned int data_len;
3895         unsigned int cur_off;
3896         unsigned int cur_page_idx;
3897         unsigned int pad_len;
3898         struct cifs_readdata *rdata = mid->callback_data;
3899         struct smb2_sync_hdr *shdr = (struct smb2_sync_hdr *)buf;
3900         struct bio_vec *bvec = NULL;
3901         struct iov_iter iter;
3902         struct kvec iov;
3903         int length;
3904         bool use_rdma_mr = false;
3905
3906         if (shdr->Command != SMB2_READ) {
3907                 cifs_server_dbg(VFS, "only big read responses are supported\n");
3908                 return -ENOTSUPP;
3909         }
3910
3911         if (server->ops->is_session_expired &&
3912             server->ops->is_session_expired(buf)) {
3913                 cifs_reconnect(server);
3914                 wake_up(&server->response_q);
3915                 return -1;
3916         }
3917
3918         if (server->ops->is_status_pending &&
3919                         server->ops->is_status_pending(buf, server))
3920                 return -1;
3921
3922         /* set up first two iov to get credits */
3923         rdata->iov[0].iov_base = buf;
3924         rdata->iov[0].iov_len = 0;
3925         rdata->iov[1].iov_base = buf;
3926         rdata->iov[1].iov_len =
3927                 min_t(unsigned int, buf_len, server->vals->read_rsp_size);
3928         cifs_dbg(FYI, "0: iov_base=%p iov_len=%zu\n",
3929                  rdata->iov[0].iov_base, rdata->iov[0].iov_len);
3930         cifs_dbg(FYI, "1: iov_base=%p iov_len=%zu\n",
3931                  rdata->iov[1].iov_base, rdata->iov[1].iov_len);
3932
3933         rdata->result = server->ops->map_error(buf, true);
3934         if (rdata->result != 0) {
3935                 cifs_dbg(FYI, "%s: server returned error %d\n",
3936                          __func__, rdata->result);
3937                 /* normal error on read response */
3938                 dequeue_mid(mid, false);
3939                 return 0;
3940         }
3941
3942         data_offset = server->ops->read_data_offset(buf);
3943 #ifdef CONFIG_CIFS_SMB_DIRECT
3944         use_rdma_mr = rdata->mr;
3945 #endif
3946         data_len = server->ops->read_data_length(buf, use_rdma_mr);
3947
3948         if (data_offset < server->vals->read_rsp_size) {
3949                 /*
3950                  * win2k8 sometimes sends an offset of 0 when the read
3951                  * is beyond the EOF. Treat it as if the data starts just after
3952                  * the header.
3953                  */
3954                 cifs_dbg(FYI, "%s: data offset (%u) inside read response header\n",
3955                          __func__, data_offset);
3956                 data_offset = server->vals->read_rsp_size;
3957         } else if (data_offset > MAX_CIFS_SMALL_BUFFER_SIZE) {
3958                 /* data_offset is beyond the end of smallbuf */
3959                 cifs_dbg(FYI, "%s: data offset (%u) beyond end of smallbuf\n",
3960                          __func__, data_offset);
3961                 rdata->result = -EIO;
3962                 dequeue_mid(mid, rdata->result);
3963                 return 0;
3964         }
3965
3966         pad_len = data_offset - server->vals->read_rsp_size;
3967
3968         if (buf_len <= data_offset) {
3969                 /* read response payload is in pages */
3970                 cur_page_idx = pad_len / PAGE_SIZE;
3971                 cur_off = pad_len % PAGE_SIZE;
3972
3973                 if (cur_page_idx != 0) {
3974                         /* data offset is beyond the 1st page of response */
3975                         cifs_dbg(FYI, "%s: data offset (%u) beyond 1st page of response\n",
3976                                  __func__, data_offset);
3977                         rdata->result = -EIO;
3978                         dequeue_mid(mid, rdata->result);
3979                         return 0;
3980                 }
3981
3982                 if (data_len > page_data_size - pad_len) {
3983                         /* data_len is corrupt -- discard frame */
3984                         rdata->result = -EIO;
3985                         dequeue_mid(mid, rdata->result);
3986                         return 0;
3987                 }
3988
3989                 rdata->result = init_read_bvec(pages, npages, page_data_size,
3990                                                cur_off, &bvec);
3991                 if (rdata->result != 0) {
3992                         dequeue_mid(mid, rdata->result);
3993                         return 0;
3994                 }
3995
3996                 iov_iter_bvec(&iter, WRITE, bvec, npages, data_len);
3997         } else if (buf_len >= data_offset + data_len) {
3998                 /* read response payload is in buf */
3999                 WARN_ONCE(npages > 0, "read data can be either in buf or in pages");
4000                 iov.iov_base = buf + data_offset;
4001                 iov.iov_len = data_len;
4002                 iov_iter_kvec(&iter, WRITE, &iov, 1, data_len);
4003         } else {
4004                 /* read response payload cannot be in both buf and pages */
4005                 WARN_ONCE(1, "buf can not contain only a part of read data");
4006                 rdata->result = -EIO;
4007                 dequeue_mid(mid, rdata->result);
4008                 return 0;
4009         }
4010
4011         length = rdata->copy_into_pages(server, rdata, &iter);
4012
4013         kfree(bvec);
4014
4015         if (length < 0)
4016                 return length;
4017
4018         dequeue_mid(mid, false);
4019         return length;
4020 }
4021
4022 struct smb2_decrypt_work {
4023         struct work_struct decrypt;
4024         struct TCP_Server_Info *server;
4025         struct page **ppages;
4026         char *buf;
4027         unsigned int npages;
4028         unsigned int len;
4029 };
4030
4031
4032 static void smb2_decrypt_offload(struct work_struct *work)
4033 {
4034         struct smb2_decrypt_work *dw = container_of(work,
4035                                 struct smb2_decrypt_work, decrypt);
4036         int i, rc;
4037         struct mid_q_entry *mid;
4038
4039         rc = decrypt_raw_data(dw->server, dw->buf, dw->server->vals->read_rsp_size,
4040                               dw->ppages, dw->npages, dw->len);
4041         if (rc) {
4042                 cifs_dbg(VFS, "error decrypting rc=%d\n", rc);
4043                 goto free_pages;
4044         }
4045
4046         mid = smb2_find_mid(dw->server, dw->buf);
4047         if (mid == NULL)
4048                 cifs_dbg(FYI, "mid not found\n");
4049         else {
4050                 mid->decrypted = true;
4051                 rc = handle_read_data(dw->server, mid, dw->buf,
4052                                       dw->server->vals->read_rsp_size,
4053                                       dw->ppages, dw->npages, dw->len);
4054         }
4055
4056         dw->server->lstrp = jiffies;
4057
4058         mid->callback(mid);
4059
4060         cifs_mid_q_entry_release(mid);
4061
4062 free_pages:
4063         for (i = dw->npages-1; i >= 0; i--)
4064                 put_page(dw->ppages[i]);
4065
4066         kfree(dw->ppages);
4067         cifs_small_buf_release(dw->buf);
4068 }
4069
4070
4071 static int
4072 receive_encrypted_read(struct TCP_Server_Info *server, struct mid_q_entry **mid,
4073                        int *num_mids)
4074 {
4075         char *buf = server->smallbuf;
4076         struct smb2_transform_hdr *tr_hdr = (struct smb2_transform_hdr *)buf;
4077         unsigned int npages;
4078         struct page **pages;
4079         unsigned int len;
4080         unsigned int buflen = server->pdu_size;
4081         int rc;
4082         int i = 0;
4083         struct smb2_decrypt_work *dw;
4084
4085         *num_mids = 1;
4086         len = min_t(unsigned int, buflen, server->vals->read_rsp_size +
4087                 sizeof(struct smb2_transform_hdr)) - HEADER_SIZE(server) + 1;
4088
4089         rc = cifs_read_from_socket(server, buf + HEADER_SIZE(server) - 1, len);
4090         if (rc < 0)
4091                 return rc;
4092         server->total_read += rc;
4093
4094         len = le32_to_cpu(tr_hdr->OriginalMessageSize) -
4095                 server->vals->read_rsp_size;
4096         npages = DIV_ROUND_UP(len, PAGE_SIZE);
4097
4098         pages = kmalloc_array(npages, sizeof(struct page *), GFP_KERNEL);
4099         if (!pages) {
4100                 rc = -ENOMEM;
4101                 goto discard_data;
4102         }
4103
4104         for (; i < npages; i++) {
4105                 pages[i] = alloc_page(GFP_KERNEL|__GFP_HIGHMEM);
4106                 if (!pages[i]) {
4107                         rc = -ENOMEM;
4108                         goto discard_data;
4109                 }
4110         }
4111
4112         /* read read data into pages */
4113         rc = read_data_into_pages(server, pages, npages, len);
4114         if (rc)
4115                 goto free_pages;
4116
4117         rc = cifs_discard_remaining_data(server);
4118         if (rc)
4119                 goto free_pages;
4120
4121         /*
4122          * For large reads, offload to different thread for better performance,
4123          * use more cores decrypting which can be expensive
4124          */
4125
4126         if ((server->min_offload) && (server->in_flight > 1) &&
4127             (server->pdu_size >= server->min_offload)) {
4128                 dw = kmalloc(sizeof(struct smb2_decrypt_work), GFP_KERNEL);
4129                 if (dw == NULL)
4130                         goto non_offloaded_decrypt;
4131
4132                 dw->buf = server->smallbuf;
4133                 server->smallbuf = (char *)cifs_small_buf_get();
4134
4135                 INIT_WORK(&dw->decrypt, smb2_decrypt_offload);
4136
4137                 dw->npages = npages;
4138                 dw->server = server;
4139                 dw->ppages = pages;
4140                 dw->len = len;
4141                 queue_work(cifsiod_wq, &dw->decrypt);
4142                 *num_mids = 0; /* worker thread takes care of finding mid */
4143                 return -1;
4144         }
4145
4146 non_offloaded_decrypt:
4147         rc = decrypt_raw_data(server, buf, server->vals->read_rsp_size,
4148                               pages, npages, len);
4149         if (rc)
4150                 goto free_pages;
4151
4152         *mid = smb2_find_mid(server, buf);
4153         if (*mid == NULL)
4154                 cifs_dbg(FYI, "mid not found\n");
4155         else {
4156                 cifs_dbg(FYI, "mid found\n");
4157                 (*mid)->decrypted = true;
4158                 rc = handle_read_data(server, *mid, buf,
4159                                       server->vals->read_rsp_size,
4160                                       pages, npages, len);
4161         }
4162
4163 free_pages:
4164         for (i = i - 1; i >= 0; i--)
4165                 put_page(pages[i]);
4166         kfree(pages);
4167         return rc;
4168 discard_data:
4169         cifs_discard_remaining_data(server);
4170         goto free_pages;
4171 }
4172
4173 static int
4174 receive_encrypted_standard(struct TCP_Server_Info *server,
4175                            struct mid_q_entry **mids, char **bufs,
4176                            int *num_mids)
4177 {
4178         int ret, length;
4179         char *buf = server->smallbuf;
4180         struct smb2_sync_hdr *shdr;
4181         unsigned int pdu_length = server->pdu_size;
4182         unsigned int buf_size;
4183         struct mid_q_entry *mid_entry;
4184         int next_is_large;
4185         char *next_buffer = NULL;
4186
4187         *num_mids = 0;
4188
4189         /* switch to large buffer if too big for a small one */
4190         if (pdu_length > MAX_CIFS_SMALL_BUFFER_SIZE) {
4191                 server->large_buf = true;
4192                 memcpy(server->bigbuf, buf, server->total_read);
4193                 buf = server->bigbuf;
4194         }
4195
4196         /* now read the rest */
4197         length = cifs_read_from_socket(server, buf + HEADER_SIZE(server) - 1,
4198                                 pdu_length - HEADER_SIZE(server) + 1);
4199         if (length < 0)
4200                 return length;
4201         server->total_read += length;
4202
4203         buf_size = pdu_length - sizeof(struct smb2_transform_hdr);
4204         length = decrypt_raw_data(server, buf, buf_size, NULL, 0, 0);
4205         if (length)
4206                 return length;
4207
4208         next_is_large = server->large_buf;
4209 one_more:
4210         shdr = (struct smb2_sync_hdr *)buf;
4211         if (shdr->NextCommand) {
4212                 if (next_is_large)
4213                         next_buffer = (char *)cifs_buf_get();
4214                 else
4215                         next_buffer = (char *)cifs_small_buf_get();
4216                 memcpy(next_buffer,
4217                        buf + le32_to_cpu(shdr->NextCommand),
4218                        pdu_length - le32_to_cpu(shdr->NextCommand));
4219         }
4220
4221         mid_entry = smb2_find_mid(server, buf);
4222         if (mid_entry == NULL)
4223                 cifs_dbg(FYI, "mid not found\n");
4224         else {
4225                 cifs_dbg(FYI, "mid found\n");
4226                 mid_entry->decrypted = true;
4227                 mid_entry->resp_buf_size = server->pdu_size;
4228         }
4229
4230         if (*num_mids >= MAX_COMPOUND) {
4231                 cifs_server_dbg(VFS, "too many PDUs in compound\n");
4232                 return -1;
4233         }
4234         bufs[*num_mids] = buf;
4235         mids[(*num_mids)++] = mid_entry;
4236
4237         if (mid_entry && mid_entry->handle)
4238                 ret = mid_entry->handle(server, mid_entry);
4239         else
4240                 ret = cifs_handle_standard(server, mid_entry);
4241
4242         if (ret == 0 && shdr->NextCommand) {
4243                 pdu_length -= le32_to_cpu(shdr->NextCommand);
4244                 server->large_buf = next_is_large;
4245                 if (next_is_large)
4246                         server->bigbuf = buf = next_buffer;
4247                 else
4248                         server->smallbuf = buf = next_buffer;
4249                 goto one_more;
4250         } else if (ret != 0) {
4251                 /*
4252                  * ret != 0 here means that we didn't get to handle_mid() thus
4253                  * server->smallbuf and server->bigbuf are still valid. We need
4254                  * to free next_buffer because it is not going to be used
4255                  * anywhere.
4256                  */
4257                 if (next_is_large)
4258                         free_rsp_buf(CIFS_LARGE_BUFFER, next_buffer);
4259                 else
4260                         free_rsp_buf(CIFS_SMALL_BUFFER, next_buffer);
4261         }
4262
4263         return ret;
4264 }
4265
4266 static int
4267 smb3_receive_transform(struct TCP_Server_Info *server,
4268                        struct mid_q_entry **mids, char **bufs, int *num_mids)
4269 {
4270         char *buf = server->smallbuf;
4271         unsigned int pdu_length = server->pdu_size;
4272         struct smb2_transform_hdr *tr_hdr = (struct smb2_transform_hdr *)buf;
4273         unsigned int orig_len = le32_to_cpu(tr_hdr->OriginalMessageSize);
4274
4275         if (pdu_length < sizeof(struct smb2_transform_hdr) +
4276                                                 sizeof(struct smb2_sync_hdr)) {
4277                 cifs_server_dbg(VFS, "Transform message is too small (%u)\n",
4278                          pdu_length);
4279                 cifs_reconnect(server);
4280                 wake_up(&server->response_q);
4281                 return -ECONNABORTED;
4282         }
4283
4284         if (pdu_length < orig_len + sizeof(struct smb2_transform_hdr)) {
4285                 cifs_server_dbg(VFS, "Transform message is broken\n");
4286                 cifs_reconnect(server);
4287                 wake_up(&server->response_q);
4288                 return -ECONNABORTED;
4289         }
4290
4291         /* TODO: add support for compounds containing READ. */
4292         if (pdu_length > CIFSMaxBufSize + MAX_HEADER_SIZE(server)) {
4293                 return receive_encrypted_read(server, &mids[0], num_mids);
4294         }
4295
4296         return receive_encrypted_standard(server, mids, bufs, num_mids);
4297 }
4298
4299 int
4300 smb3_handle_read_data(struct TCP_Server_Info *server, struct mid_q_entry *mid)
4301 {
4302         char *buf = server->large_buf ? server->bigbuf : server->smallbuf;
4303
4304         return handle_read_data(server, mid, buf, server->pdu_size,
4305                                 NULL, 0, 0);
4306 }
4307
4308 static int
4309 smb2_next_header(char *buf)
4310 {
4311         struct smb2_sync_hdr *hdr = (struct smb2_sync_hdr *)buf;
4312         struct smb2_transform_hdr *t_hdr = (struct smb2_transform_hdr *)buf;
4313
4314         if (hdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM)
4315                 return sizeof(struct smb2_transform_hdr) +
4316                   le32_to_cpu(t_hdr->OriginalMessageSize);
4317
4318         return le32_to_cpu(hdr->NextCommand);
4319 }
4320
4321 static int
4322 smb2_make_node(unsigned int xid, struct inode *inode,
4323                struct dentry *dentry, struct cifs_tcon *tcon,
4324                char *full_path, umode_t mode, dev_t dev)
4325 {
4326         struct cifs_sb_info *cifs_sb = CIFS_SB(inode->i_sb);
4327         int rc = -EPERM;
4328         int create_options = CREATE_NOT_DIR | CREATE_OPTION_SPECIAL;
4329         FILE_ALL_INFO *buf = NULL;
4330         struct cifs_io_parms io_parms;
4331         __u32 oplock = 0;
4332         struct cifs_fid fid;
4333         struct cifs_open_parms oparms;
4334         unsigned int bytes_written;
4335         struct win_dev *pdev;
4336         struct kvec iov[2];
4337
4338         /*
4339          * Check if mounted with mount parm 'sfu' mount parm.
4340          * SFU emulation should work with all servers, but only
4341          * supports block and char device (no socket & fifo),
4342          * and was used by default in earlier versions of Windows
4343          */
4344         if (!(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_UNX_EMUL))
4345                 goto out;
4346
4347         /*
4348          * TODO: Add ability to create instead via reparse point. Windows (e.g.
4349          * their current NFS server) uses this approach to expose special files
4350          * over SMB2/SMB3 and Samba will do this with SMB3.1.1 POSIX Extensions
4351          */
4352
4353         if (!S_ISCHR(mode) && !S_ISBLK(mode))
4354                 goto out;
4355
4356         cifs_dbg(FYI, "sfu compat create special file\n");
4357
4358         buf = kmalloc(sizeof(FILE_ALL_INFO), GFP_KERNEL);
4359         if (buf == NULL) {
4360                 rc = -ENOMEM;
4361                 goto out;
4362         }
4363
4364         if (backup_cred(cifs_sb))
4365                 create_options |= CREATE_OPEN_BACKUP_INTENT;
4366
4367         oparms.tcon = tcon;
4368         oparms.cifs_sb = cifs_sb;
4369         oparms.desired_access = GENERIC_WRITE;
4370         oparms.create_options = create_options;
4371         oparms.disposition = FILE_CREATE;
4372         oparms.path = full_path;
4373         oparms.fid = &fid;
4374         oparms.reconnect = false;
4375
4376         if (tcon->ses->server->oplocks)
4377                 oplock = REQ_OPLOCK;
4378         else
4379                 oplock = 0;
4380         rc = tcon->ses->server->ops->open(xid, &oparms, &oplock, buf);
4381         if (rc)
4382                 goto out;
4383
4384         /*
4385          * BB Do not bother to decode buf since no local inode yet to put
4386          * timestamps in, but we can reuse it safely.
4387          */
4388
4389         pdev = (struct win_dev *)buf;
4390         io_parms.pid = current->tgid;
4391         io_parms.tcon = tcon;
4392         io_parms.offset = 0;
4393         io_parms.length = sizeof(struct win_dev);
4394         iov[1].iov_base = buf;
4395         iov[1].iov_len = sizeof(struct win_dev);
4396         if (S_ISCHR(mode)) {
4397                 memcpy(pdev->type, "IntxCHR", 8);
4398                 pdev->major = cpu_to_le64(MAJOR(dev));
4399                 pdev->minor = cpu_to_le64(MINOR(dev));
4400                 rc = tcon->ses->server->ops->sync_write(xid, &fid, &io_parms,
4401                                                         &bytes_written, iov, 1);
4402         } else if (S_ISBLK(mode)) {
4403                 memcpy(pdev->type, "IntxBLK", 8);
4404                 pdev->major = cpu_to_le64(MAJOR(dev));
4405                 pdev->minor = cpu_to_le64(MINOR(dev));
4406                 rc = tcon->ses->server->ops->sync_write(xid, &fid, &io_parms,
4407                                                         &bytes_written, iov, 1);
4408         }
4409         tcon->ses->server->ops->close(xid, tcon, &fid);
4410         d_drop(dentry);
4411
4412         /* FIXME: add code here to set EAs */
4413 out:
4414         kfree(buf);
4415         return rc;
4416 }
4417
4418
4419 struct smb_version_operations smb20_operations = {
4420         .compare_fids = smb2_compare_fids,
4421         .setup_request = smb2_setup_request,
4422         .setup_async_request = smb2_setup_async_request,
4423         .check_receive = smb2_check_receive,
4424         .add_credits = smb2_add_credits,
4425         .set_credits = smb2_set_credits,
4426         .get_credits_field = smb2_get_credits_field,
4427         .get_credits = smb2_get_credits,
4428         .wait_mtu_credits = cifs_wait_mtu_credits,
4429         .get_next_mid = smb2_get_next_mid,
4430         .revert_current_mid = smb2_revert_current_mid,
4431         .read_data_offset = smb2_read_data_offset,
4432         .read_data_length = smb2_read_data_length,
4433         .map_error = map_smb2_to_linux_error,
4434         .find_mid = smb2_find_mid,
4435         .check_message = smb2_check_message,
4436         .dump_detail = smb2_dump_detail,
4437         .clear_stats = smb2_clear_stats,
4438         .print_stats = smb2_print_stats,
4439         .is_oplock_break = smb2_is_valid_oplock_break,
4440         .handle_cancelled_mid = smb2_handle_cancelled_mid,
4441         .downgrade_oplock = smb2_downgrade_oplock,
4442         .need_neg = smb2_need_neg,
4443         .negotiate = smb2_negotiate,
4444         .negotiate_wsize = smb2_negotiate_wsize,
4445         .negotiate_rsize = smb2_negotiate_rsize,
4446         .sess_setup = SMB2_sess_setup,
4447         .logoff = SMB2_logoff,
4448         .tree_connect = SMB2_tcon,
4449         .tree_disconnect = SMB2_tdis,
4450         .qfs_tcon = smb2_qfs_tcon,
4451         .is_path_accessible = smb2_is_path_accessible,
4452         .can_echo = smb2_can_echo,
4453         .echo = SMB2_echo,
4454         .query_path_info = smb2_query_path_info,
4455         .get_srv_inum = smb2_get_srv_inum,
4456         .query_file_info = smb2_query_file_info,
4457         .set_path_size = smb2_set_path_size,
4458         .set_file_size = smb2_set_file_size,
4459         .set_file_info = smb2_set_file_info,
4460         .set_compression = smb2_set_compression,
4461         .mkdir = smb2_mkdir,
4462         .mkdir_setinfo = smb2_mkdir_setinfo,
4463         .rmdir = smb2_rmdir,
4464         .unlink = smb2_unlink,
4465         .rename = smb2_rename_path,
4466         .create_hardlink = smb2_create_hardlink,
4467         .query_symlink = smb2_query_symlink,
4468         .query_mf_symlink = smb3_query_mf_symlink,
4469         .create_mf_symlink = smb3_create_mf_symlink,
4470         .open = smb2_open_file,
4471         .set_fid = smb2_set_fid,
4472         .close = smb2_close_file,
4473         .flush = smb2_flush_file,
4474         .async_readv = smb2_async_readv,
4475         .async_writev = smb2_async_writev,
4476         .sync_read = smb2_sync_read,
4477         .sync_write = smb2_sync_write,
4478         .query_dir_first = smb2_query_dir_first,
4479         .query_dir_next = smb2_query_dir_next,
4480         .close_dir = smb2_close_dir,
4481         .calc_smb_size = smb2_calc_size,
4482         .is_status_pending = smb2_is_status_pending,
4483         .is_session_expired = smb2_is_session_expired,
4484         .oplock_response = smb2_oplock_response,
4485         .queryfs = smb2_queryfs,
4486         .mand_lock = smb2_mand_lock,
4487         .mand_unlock_range = smb2_unlock_range,
4488         .push_mand_locks = smb2_push_mandatory_locks,
4489         .get_lease_key = smb2_get_lease_key,
4490         .set_lease_key = smb2_set_lease_key,
4491         .new_lease_key = smb2_new_lease_key,
4492         .calc_signature = smb2_calc_signature,
4493         .is_read_op = smb2_is_read_op,
4494         .set_oplock_level = smb2_set_oplock_level,
4495         .create_lease_buf = smb2_create_lease_buf,
4496         .parse_lease_buf = smb2_parse_lease_buf,
4497         .copychunk_range = smb2_copychunk_range,
4498         .wp_retry_size = smb2_wp_retry_size,
4499         .dir_needs_close = smb2_dir_needs_close,
4500         .get_dfs_refer = smb2_get_dfs_refer,
4501         .select_sectype = smb2_select_sectype,
4502 #ifdef CONFIG_CIFS_XATTR
4503         .query_all_EAs = smb2_query_eas,
4504         .set_EA = smb2_set_ea,
4505 #endif /* CIFS_XATTR */
4506         .get_acl = get_smb2_acl,
4507         .get_acl_by_fid = get_smb2_acl_by_fid,
4508         .set_acl = set_smb2_acl,
4509         .next_header = smb2_next_header,
4510         .ioctl_query_info = smb2_ioctl_query_info,
4511         .make_node = smb2_make_node,
4512         .fiemap = smb3_fiemap,
4513         .llseek = smb3_llseek,
4514 };
4515
4516 struct smb_version_operations smb21_operations = {
4517         .compare_fids = smb2_compare_fids,
4518         .setup_request = smb2_setup_request,
4519         .setup_async_request = smb2_setup_async_request,
4520         .check_receive = smb2_check_receive,
4521         .add_credits = smb2_add_credits,
4522         .set_credits = smb2_set_credits,
4523         .get_credits_field = smb2_get_credits_field,
4524         .get_credits = smb2_get_credits,
4525         .wait_mtu_credits = smb2_wait_mtu_credits,
4526         .adjust_credits = smb2_adjust_credits,
4527         .get_next_mid = smb2_get_next_mid,
4528         .revert_current_mid = smb2_revert_current_mid,
4529         .read_data_offset = smb2_read_data_offset,
4530         .read_data_length = smb2_read_data_length,
4531         .map_error = map_smb2_to_linux_error,
4532         .find_mid = smb2_find_mid,
4533         .check_message = smb2_check_message,
4534         .dump_detail = smb2_dump_detail,
4535         .clear_stats = smb2_clear_stats,
4536         .print_stats = smb2_print_stats,
4537         .is_oplock_break = smb2_is_valid_oplock_break,
4538         .handle_cancelled_mid = smb2_handle_cancelled_mid,
4539         .downgrade_oplock = smb21_downgrade_oplock,
4540         .need_neg = smb2_need_neg,
4541         .negotiate = smb2_negotiate,
4542         .negotiate_wsize = smb2_negotiate_wsize,
4543         .negotiate_rsize = smb2_negotiate_rsize,
4544         .sess_setup = SMB2_sess_setup,
4545         .logoff = SMB2_logoff,
4546         .tree_connect = SMB2_tcon,
4547         .tree_disconnect = SMB2_tdis,
4548         .qfs_tcon = smb2_qfs_tcon,
4549         .is_path_accessible = smb2_is_path_accessible,
4550         .can_echo = smb2_can_echo,
4551         .echo = SMB2_echo,
4552         .query_path_info = smb2_query_path_info,
4553         .get_srv_inum = smb2_get_srv_inum,
4554         .query_file_info = smb2_query_file_info,
4555         .set_path_size = smb2_set_path_size,
4556         .set_file_size = smb2_set_file_size,
4557         .set_file_info = smb2_set_file_info,
4558         .set_compression = smb2_set_compression,
4559         .mkdir = smb2_mkdir,
4560         .mkdir_setinfo = smb2_mkdir_setinfo,
4561         .rmdir = smb2_rmdir,
4562         .unlink = smb2_unlink,
4563         .rename = smb2_rename_path,
4564         .create_hardlink = smb2_create_hardlink,
4565         .query_symlink = smb2_query_symlink,
4566         .query_mf_symlink = smb3_query_mf_symlink,
4567         .create_mf_symlink = smb3_create_mf_symlink,
4568         .open = smb2_open_file,
4569         .set_fid = smb2_set_fid,
4570         .close = smb2_close_file,
4571         .flush = smb2_flush_file,
4572         .async_readv = smb2_async_readv,
4573         .async_writev = smb2_async_writev,
4574         .sync_read = smb2_sync_read,
4575         .sync_write = smb2_sync_write,
4576         .query_dir_first = smb2_query_dir_first,
4577         .query_dir_next = smb2_query_dir_next,
4578         .close_dir = smb2_close_dir,
4579         .calc_smb_size = smb2_calc_size,
4580         .is_status_pending = smb2_is_status_pending,
4581         .is_session_expired = smb2_is_session_expired,
4582         .oplock_response = smb2_oplock_response,
4583         .queryfs = smb2_queryfs,
4584         .mand_lock = smb2_mand_lock,
4585         .mand_unlock_range = smb2_unlock_range,
4586         .push_mand_locks = smb2_push_mandatory_locks,
4587         .get_lease_key = smb2_get_lease_key,
4588         .set_lease_key = smb2_set_lease_key,
4589         .new_lease_key = smb2_new_lease_key,
4590         .calc_signature = smb2_calc_signature,
4591         .is_read_op = smb21_is_read_op,
4592         .set_oplock_level = smb21_set_oplock_level,
4593         .create_lease_buf = smb2_create_lease_buf,
4594         .parse_lease_buf = smb2_parse_lease_buf,
4595         .copychunk_range = smb2_copychunk_range,
4596         .wp_retry_size = smb2_wp_retry_size,
4597         .dir_needs_close = smb2_dir_needs_close,
4598         .enum_snapshots = smb3_enum_snapshots,
4599         .get_dfs_refer = smb2_get_dfs_refer,
4600         .select_sectype = smb2_select_sectype,
4601 #ifdef CONFIG_CIFS_XATTR
4602         .query_all_EAs = smb2_query_eas,
4603         .set_EA = smb2_set_ea,
4604 #endif /* CIFS_XATTR */
4605         .get_acl = get_smb2_acl,
4606         .get_acl_by_fid = get_smb2_acl_by_fid,
4607         .set_acl = set_smb2_acl,
4608         .next_header = smb2_next_header,
4609         .ioctl_query_info = smb2_ioctl_query_info,
4610         .make_node = smb2_make_node,
4611         .fiemap = smb3_fiemap,
4612         .llseek = smb3_llseek,
4613 };
4614
4615 struct smb_version_operations smb30_operations = {
4616         .compare_fids = smb2_compare_fids,
4617         .setup_request = smb2_setup_request,
4618         .setup_async_request = smb2_setup_async_request,
4619         .check_receive = smb2_check_receive,
4620         .add_credits = smb2_add_credits,
4621         .set_credits = smb2_set_credits,
4622         .get_credits_field = smb2_get_credits_field,
4623         .get_credits = smb2_get_credits,
4624         .wait_mtu_credits = smb2_wait_mtu_credits,
4625         .adjust_credits = smb2_adjust_credits,
4626         .get_next_mid = smb2_get_next_mid,
4627         .revert_current_mid = smb2_revert_current_mid,
4628         .read_data_offset = smb2_read_data_offset,
4629         .read_data_length = smb2_read_data_length,
4630         .map_error = map_smb2_to_linux_error,
4631         .find_mid = smb2_find_mid,
4632         .check_message = smb2_check_message,
4633         .dump_detail = smb2_dump_detail,
4634         .clear_stats = smb2_clear_stats,
4635         .print_stats = smb2_print_stats,
4636         .dump_share_caps = smb2_dump_share_caps,
4637         .is_oplock_break = smb2_is_valid_oplock_break,
4638         .handle_cancelled_mid = smb2_handle_cancelled_mid,
4639         .downgrade_oplock = smb21_downgrade_oplock,
4640         .need_neg = smb2_need_neg,
4641         .negotiate = smb2_negotiate,
4642         .negotiate_wsize = smb3_negotiate_wsize,
4643         .negotiate_rsize = smb3_negotiate_rsize,
4644         .sess_setup = SMB2_sess_setup,
4645         .logoff = SMB2_logoff,
4646         .tree_connect = SMB2_tcon,
4647         .tree_disconnect = SMB2_tdis,
4648         .qfs_tcon = smb3_qfs_tcon,
4649         .is_path_accessible = smb2_is_path_accessible,
4650         .can_echo = smb2_can_echo,
4651         .echo = SMB2_echo,
4652         .query_path_info = smb2_query_path_info,
4653         .get_srv_inum = smb2_get_srv_inum,
4654         .query_file_info = smb2_query_file_info,
4655         .set_path_size = smb2_set_path_size,
4656         .set_file_size = smb2_set_file_size,
4657         .set_file_info = smb2_set_file_info,
4658         .set_compression = smb2_set_compression,
4659         .mkdir = smb2_mkdir,
4660         .mkdir_setinfo = smb2_mkdir_setinfo,
4661         .rmdir = smb2_rmdir,
4662         .unlink = smb2_unlink,
4663         .rename = smb2_rename_path,
4664         .create_hardlink = smb2_create_hardlink,
4665         .query_symlink = smb2_query_symlink,
4666         .query_mf_symlink = smb3_query_mf_symlink,
4667         .create_mf_symlink = smb3_create_mf_symlink,
4668         .open = smb2_open_file,
4669         .set_fid = smb2_set_fid,
4670         .close = smb2_close_file,
4671         .flush = smb2_flush_file,
4672         .async_readv = smb2_async_readv,
4673         .async_writev = smb2_async_writev,
4674         .sync_read = smb2_sync_read,
4675         .sync_write = smb2_sync_write,
4676         .query_dir_first = smb2_query_dir_first,
4677         .query_dir_next = smb2_query_dir_next,
4678         .close_dir = smb2_close_dir,
4679         .calc_smb_size = smb2_calc_size,
4680         .is_status_pending = smb2_is_status_pending,
4681         .is_session_expired = smb2_is_session_expired,
4682         .oplock_response = smb2_oplock_response,
4683         .queryfs = smb2_queryfs,
4684         .mand_lock = smb2_mand_lock,
4685         .mand_unlock_range = smb2_unlock_range,
4686         .push_mand_locks = smb2_push_mandatory_locks,
4687         .get_lease_key = smb2_get_lease_key,
4688         .set_lease_key = smb2_set_lease_key,
4689         .new_lease_key = smb2_new_lease_key,
4690         .generate_signingkey = generate_smb30signingkey,
4691         .calc_signature = smb3_calc_signature,
4692         .set_integrity  = smb3_set_integrity,
4693         .is_read_op = smb21_is_read_op,
4694         .set_oplock_level = smb3_set_oplock_level,
4695         .create_lease_buf = smb3_create_lease_buf,
4696         .parse_lease_buf = smb3_parse_lease_buf,
4697         .copychunk_range = smb2_copychunk_range,
4698         .duplicate_extents = smb2_duplicate_extents,
4699         .validate_negotiate = smb3_validate_negotiate,
4700         .wp_retry_size = smb2_wp_retry_size,
4701         .dir_needs_close = smb2_dir_needs_close,
4702         .fallocate = smb3_fallocate,
4703         .enum_snapshots = smb3_enum_snapshots,
4704         .init_transform_rq = smb3_init_transform_rq,
4705         .is_transform_hdr = smb3_is_transform_hdr,
4706         .receive_transform = smb3_receive_transform,
4707         .get_dfs_refer = smb2_get_dfs_refer,
4708         .select_sectype = smb2_select_sectype,
4709 #ifdef CONFIG_CIFS_XATTR
4710         .query_all_EAs = smb2_query_eas,
4711         .set_EA = smb2_set_ea,
4712 #endif /* CIFS_XATTR */
4713         .get_acl = get_smb2_acl,
4714         .get_acl_by_fid = get_smb2_acl_by_fid,
4715         .set_acl = set_smb2_acl,
4716         .next_header = smb2_next_header,
4717         .ioctl_query_info = smb2_ioctl_query_info,
4718         .make_node = smb2_make_node,
4719         .fiemap = smb3_fiemap,
4720         .llseek = smb3_llseek,
4721 };
4722
4723 struct smb_version_operations smb311_operations = {
4724         .compare_fids = smb2_compare_fids,
4725         .setup_request = smb2_setup_request,
4726         .setup_async_request = smb2_setup_async_request,
4727         .check_receive = smb2_check_receive,
4728         .add_credits = smb2_add_credits,
4729         .set_credits = smb2_set_credits,
4730         .get_credits_field = smb2_get_credits_field,
4731         .get_credits = smb2_get_credits,
4732         .wait_mtu_credits = smb2_wait_mtu_credits,
4733         .adjust_credits = smb2_adjust_credits,
4734         .get_next_mid = smb2_get_next_mid,
4735         .revert_current_mid = smb2_revert_current_mid,
4736         .read_data_offset = smb2_read_data_offset,
4737         .read_data_length = smb2_read_data_length,
4738         .map_error = map_smb2_to_linux_error,
4739         .find_mid = smb2_find_mid,
4740         .check_message = smb2_check_message,
4741         .dump_detail = smb2_dump_detail,
4742         .clear_stats = smb2_clear_stats,
4743         .print_stats = smb2_print_stats,
4744         .dump_share_caps = smb2_dump_share_caps,
4745         .is_oplock_break = smb2_is_valid_oplock_break,
4746         .handle_cancelled_mid = smb2_handle_cancelled_mid,
4747         .downgrade_oplock = smb21_downgrade_oplock,
4748         .need_neg = smb2_need_neg,
4749         .negotiate = smb2_negotiate,
4750         .negotiate_wsize = smb3_negotiate_wsize,
4751         .negotiate_rsize = smb3_negotiate_rsize,
4752         .sess_setup = SMB2_sess_setup,
4753         .logoff = SMB2_logoff,
4754         .tree_connect = SMB2_tcon,
4755         .tree_disconnect = SMB2_tdis,
4756         .qfs_tcon = smb3_qfs_tcon,
4757         .is_path_accessible = smb2_is_path_accessible,
4758         .can_echo = smb2_can_echo,
4759         .echo = SMB2_echo,
4760         .query_path_info = smb2_query_path_info,
4761         .get_srv_inum = smb2_get_srv_inum,
4762         .query_file_info = smb2_query_file_info,
4763         .set_path_size = smb2_set_path_size,
4764         .set_file_size = smb2_set_file_size,
4765         .set_file_info = smb2_set_file_info,
4766         .set_compression = smb2_set_compression,
4767         .mkdir = smb2_mkdir,
4768         .mkdir_setinfo = smb2_mkdir_setinfo,
4769         .posix_mkdir = smb311_posix_mkdir,
4770         .rmdir = smb2_rmdir,
4771         .unlink = smb2_unlink,
4772         .rename = smb2_rename_path,
4773         .create_hardlink = smb2_create_hardlink,
4774         .query_symlink = smb2_query_symlink,
4775         .query_mf_symlink = smb3_query_mf_symlink,
4776         .create_mf_symlink = smb3_create_mf_symlink,
4777         .open = smb2_open_file,
4778         .set_fid = smb2_set_fid,
4779         .close = smb2_close_file,
4780         .flush = smb2_flush_file,
4781         .async_readv = smb2_async_readv,
4782         .async_writev = smb2_async_writev,
4783         .sync_read = smb2_sync_read,
4784         .sync_write = smb2_sync_write,
4785         .query_dir_first = smb2_query_dir_first,
4786         .query_dir_next = smb2_query_dir_next,
4787         .close_dir = smb2_close_dir,
4788         .calc_smb_size = smb2_calc_size,
4789         .is_status_pending = smb2_is_status_pending,
4790         .is_session_expired = smb2_is_session_expired,
4791         .oplock_response = smb2_oplock_response,
4792         .queryfs = smb311_queryfs,
4793         .mand_lock = smb2_mand_lock,
4794         .mand_unlock_range = smb2_unlock_range,
4795         .push_mand_locks = smb2_push_mandatory_locks,
4796         .get_lease_key = smb2_get_lease_key,
4797         .set_lease_key = smb2_set_lease_key,
4798         .new_lease_key = smb2_new_lease_key,
4799         .generate_signingkey = generate_smb311signingkey,
4800         .calc_signature = smb3_calc_signature,
4801         .set_integrity  = smb3_set_integrity,
4802         .is_read_op = smb21_is_read_op,
4803         .set_oplock_level = smb3_set_oplock_level,
4804         .create_lease_buf = smb3_create_lease_buf,
4805         .parse_lease_buf = smb3_parse_lease_buf,
4806         .copychunk_range = smb2_copychunk_range,
4807         .duplicate_extents = smb2_duplicate_extents,
4808 /*      .validate_negotiate = smb3_validate_negotiate, */ /* not used in 3.11 */
4809         .wp_retry_size = smb2_wp_retry_size,
4810         .dir_needs_close = smb2_dir_needs_close,
4811         .fallocate = smb3_fallocate,
4812         .enum_snapshots = smb3_enum_snapshots,
4813         .init_transform_rq = smb3_init_transform_rq,
4814         .is_transform_hdr = smb3_is_transform_hdr,
4815         .receive_transform = smb3_receive_transform,
4816         .get_dfs_refer = smb2_get_dfs_refer,
4817         .select_sectype = smb2_select_sectype,
4818 #ifdef CONFIG_CIFS_XATTR
4819         .query_all_EAs = smb2_query_eas,
4820         .set_EA = smb2_set_ea,
4821 #endif /* CIFS_XATTR */
4822         .get_acl = get_smb2_acl,
4823         .get_acl_by_fid = get_smb2_acl_by_fid,
4824         .set_acl = set_smb2_acl,
4825         .next_header = smb2_next_header,
4826         .ioctl_query_info = smb2_ioctl_query_info,
4827         .make_node = smb2_make_node,
4828         .fiemap = smb3_fiemap,
4829         .llseek = smb3_llseek,
4830 };
4831
4832 struct smb_version_values smb20_values = {
4833         .version_string = SMB20_VERSION_STRING,
4834         .protocol_id = SMB20_PROT_ID,
4835         .req_capabilities = 0, /* MBZ */
4836         .large_lock_type = 0,
4837         .exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE_LOCK,
4838         .shared_lock_type = SMB2_LOCKFLAG_SHARED_LOCK,
4839         .unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
4840         .header_size = sizeof(struct smb2_sync_hdr),
4841         .header_preamble_size = 0,
4842         .max_header_size = MAX_SMB2_HDR_SIZE,
4843         .read_rsp_size = sizeof(struct smb2_read_rsp) - 1,
4844         .lock_cmd = SMB2_LOCK,
4845         .cap_unix = 0,
4846         .cap_nt_find = SMB2_NT_FIND,
4847         .cap_large_files = SMB2_LARGE_FILES,
4848         .signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
4849         .signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
4850         .create_lease_size = sizeof(struct create_lease),
4851 };
4852
4853 struct smb_version_values smb21_values = {
4854         .version_string = SMB21_VERSION_STRING,
4855         .protocol_id = SMB21_PROT_ID,
4856         .req_capabilities = 0, /* MBZ on negotiate req until SMB3 dialect */
4857         .large_lock_type = 0,
4858         .exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE_LOCK,
4859         .shared_lock_type = SMB2_LOCKFLAG_SHARED_LOCK,
4860         .unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
4861         .header_size = sizeof(struct smb2_sync_hdr),
4862         .header_preamble_size = 0,
4863         .max_header_size = MAX_SMB2_HDR_SIZE,
4864         .read_rsp_size = sizeof(struct smb2_read_rsp) - 1,
4865         .lock_cmd = SMB2_LOCK,
4866         .cap_unix = 0,
4867         .cap_nt_find = SMB2_NT_FIND,
4868         .cap_large_files = SMB2_LARGE_FILES,
4869         .signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
4870         .signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
4871         .create_lease_size = sizeof(struct create_lease),
4872 };
4873
4874 struct smb_version_values smb3any_values = {
4875         .version_string = SMB3ANY_VERSION_STRING,
4876         .protocol_id = SMB302_PROT_ID, /* doesn't matter, send protocol array */
4877         .req_capabilities = SMB2_GLOBAL_CAP_DFS | SMB2_GLOBAL_CAP_LEASING | SMB2_GLOBAL_CAP_LARGE_MTU | SMB2_GLOBAL_CAP_PERSISTENT_HANDLES | SMB2_GLOBAL_CAP_ENCRYPTION | SMB2_GLOBAL_CAP_DIRECTORY_LEASING,
4878         .large_lock_type = 0,
4879         .exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE_LOCK,
4880         .shared_lock_type = SMB2_LOCKFLAG_SHARED_LOCK,
4881         .unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
4882         .header_size = sizeof(struct smb2_sync_hdr),
4883         .header_preamble_size = 0,
4884         .max_header_size = MAX_SMB2_HDR_SIZE,
4885         .read_rsp_size = sizeof(struct smb2_read_rsp) - 1,
4886         .lock_cmd = SMB2_LOCK,
4887         .cap_unix = 0,
4888         .cap_nt_find = SMB2_NT_FIND,
4889         .cap_large_files = SMB2_LARGE_FILES,
4890         .signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
4891         .signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
4892         .create_lease_size = sizeof(struct create_lease_v2),
4893 };
4894
4895 struct smb_version_values smbdefault_values = {
4896         .version_string = SMBDEFAULT_VERSION_STRING,
4897         .protocol_id = SMB302_PROT_ID, /* doesn't matter, send protocol array */
4898         .req_capabilities = SMB2_GLOBAL_CAP_DFS | SMB2_GLOBAL_CAP_LEASING | SMB2_GLOBAL_CAP_LARGE_MTU | SMB2_GLOBAL_CAP_PERSISTENT_HANDLES | SMB2_GLOBAL_CAP_ENCRYPTION | SMB2_GLOBAL_CAP_DIRECTORY_LEASING,
4899         .large_lock_type = 0,
4900         .exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE_LOCK,
4901         .shared_lock_type = SMB2_LOCKFLAG_SHARED_LOCK,
4902         .unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
4903         .header_size = sizeof(struct smb2_sync_hdr),
4904         .header_preamble_size = 0,
4905         .max_header_size = MAX_SMB2_HDR_SIZE,
4906         .read_rsp_size = sizeof(struct smb2_read_rsp) - 1,
4907         .lock_cmd = SMB2_LOCK,
4908         .cap_unix = 0,
4909         .cap_nt_find = SMB2_NT_FIND,
4910         .cap_large_files = SMB2_LARGE_FILES,
4911         .signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
4912         .signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
4913         .create_lease_size = sizeof(struct create_lease_v2),
4914 };
4915
4916 struct smb_version_values smb30_values = {
4917         .version_string = SMB30_VERSION_STRING,
4918         .protocol_id = SMB30_PROT_ID,
4919         .req_capabilities = SMB2_GLOBAL_CAP_DFS | SMB2_GLOBAL_CAP_LEASING | SMB2_GLOBAL_CAP_LARGE_MTU | SMB2_GLOBAL_CAP_PERSISTENT_HANDLES | SMB2_GLOBAL_CAP_ENCRYPTION | SMB2_GLOBAL_CAP_DIRECTORY_LEASING,
4920         .large_lock_type = 0,
4921         .exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE_LOCK,
4922         .shared_lock_type = SMB2_LOCKFLAG_SHARED_LOCK,
4923         .unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
4924         .header_size = sizeof(struct smb2_sync_hdr),
4925         .header_preamble_size = 0,
4926         .max_header_size = MAX_SMB2_HDR_SIZE,
4927         .read_rsp_size = sizeof(struct smb2_read_rsp) - 1,
4928         .lock_cmd = SMB2_LOCK,
4929         .cap_unix = 0,
4930         .cap_nt_find = SMB2_NT_FIND,
4931         .cap_large_files = SMB2_LARGE_FILES,
4932         .signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
4933         .signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
4934         .create_lease_size = sizeof(struct create_lease_v2),
4935 };
4936
4937 struct smb_version_values smb302_values = {
4938         .version_string = SMB302_VERSION_STRING,
4939         .protocol_id = SMB302_PROT_ID,
4940         .req_capabilities = SMB2_GLOBAL_CAP_DFS | SMB2_GLOBAL_CAP_LEASING | SMB2_GLOBAL_CAP_LARGE_MTU | SMB2_GLOBAL_CAP_PERSISTENT_HANDLES | SMB2_GLOBAL_CAP_ENCRYPTION | SMB2_GLOBAL_CAP_DIRECTORY_LEASING,
4941         .large_lock_type = 0,
4942         .exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE_LOCK,
4943         .shared_lock_type = SMB2_LOCKFLAG_SHARED_LOCK,
4944         .unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
4945         .header_size = sizeof(struct smb2_sync_hdr),
4946         .header_preamble_size = 0,
4947         .max_header_size = MAX_SMB2_HDR_SIZE,
4948         .read_rsp_size = sizeof(struct smb2_read_rsp) - 1,
4949         .lock_cmd = SMB2_LOCK,
4950         .cap_unix = 0,
4951         .cap_nt_find = SMB2_NT_FIND,
4952         .cap_large_files = SMB2_LARGE_FILES,
4953         .signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
4954         .signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
4955         .create_lease_size = sizeof(struct create_lease_v2),
4956 };
4957
4958 struct smb_version_values smb311_values = {
4959         .version_string = SMB311_VERSION_STRING,
4960         .protocol_id = SMB311_PROT_ID,
4961         .req_capabilities = SMB2_GLOBAL_CAP_DFS | SMB2_GLOBAL_CAP_LEASING | SMB2_GLOBAL_CAP_LARGE_MTU | SMB2_GLOBAL_CAP_PERSISTENT_HANDLES | SMB2_GLOBAL_CAP_ENCRYPTION | SMB2_GLOBAL_CAP_DIRECTORY_LEASING,
4962         .large_lock_type = 0,
4963         .exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE_LOCK,
4964         .shared_lock_type = SMB2_LOCKFLAG_SHARED_LOCK,
4965         .unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
4966         .header_size = sizeof(struct smb2_sync_hdr),
4967         .header_preamble_size = 0,
4968         .max_header_size = MAX_SMB2_HDR_SIZE,
4969         .read_rsp_size = sizeof(struct smb2_read_rsp) - 1,
4970         .lock_cmd = SMB2_LOCK,
4971         .cap_unix = 0,
4972         .cap_nt_find = SMB2_NT_FIND,
4973         .cap_large_files = SMB2_LARGE_FILES,
4974         .signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
4975         .signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
4976         .create_lease_size = sizeof(struct create_lease_v2),
4977 };