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