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