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