xref: /linux/fs/smb/client/smb2ops.c (revision bb29b957eaaa15be33243550d9ee576c2d601669)
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 	num = out_data_len / sizeof(struct file_allocated_range_buffer);
4364 	for (i = 0; i < num; i++) {
4365 		flags = 0;
4366 		if (i == num - 1 && last_blob)
4367 			flags |= FIEMAP_EXTENT_LAST;
4368 
4369 		rc = fiemap_fill_next_extent(fei,
4370 				le64_to_cpu(out_data[i].file_offset),
4371 				le64_to_cpu(out_data[i].file_offset),
4372 				le64_to_cpu(out_data[i].length),
4373 				flags);
4374 		if (rc < 0)
4375 			goto out;
4376 		if (rc == 1) {
4377 			rc = 0;
4378 			goto out;
4379 		}
4380 	}
4381 
4382 	if (!last_blob) {
4383 		next = le64_to_cpu(out_data[num - 1].file_offset) +
4384 		  le64_to_cpu(out_data[num - 1].length);
4385 		len = len - (next - start);
4386 		start = next;
4387 		goto again;
4388 	}
4389 
4390  out:
4391 	free_xid(xid);
4392 	kfree(out_data);
4393 	return rc;
4394 }
4395 
4396 static long smb3_fallocate(struct file *file, struct cifs_tcon *tcon, int mode,
4397 			   loff_t off, loff_t len)
4398 {
4399 	/* KEEP_SIZE already checked for by do_fallocate */
4400 	if (mode & FALLOC_FL_PUNCH_HOLE)
4401 		return smb3_punch_hole(file, tcon, off, len);
4402 	else if (mode & FALLOC_FL_ZERO_RANGE) {
4403 		if (mode & FALLOC_FL_KEEP_SIZE)
4404 			return smb3_zero_range(file, tcon, off, len, true);
4405 		return smb3_zero_range(file, tcon, off, len, false);
4406 	} else if (mode == FALLOC_FL_KEEP_SIZE)
4407 		return smb3_simple_falloc(file, tcon, off, len, true);
4408 	else if (mode == FALLOC_FL_COLLAPSE_RANGE)
4409 		return smb3_collapse_range(file, tcon, off, len);
4410 	else if (mode == FALLOC_FL_INSERT_RANGE)
4411 		return smb3_insert_range(file, tcon, off, len);
4412 	else if (mode == FALLOC_FL_ALLOCATE_RANGE)
4413 		return smb3_simple_falloc(file, tcon, off, len, false);
4414 
4415 	return -EOPNOTSUPP;
4416 }
4417 
4418 static void
4419 smb2_downgrade_oplock(struct TCP_Server_Info *server,
4420 		      struct cifsInodeInfo *cinode, __u32 oplock,
4421 		      __u16 epoch, bool *purge_cache)
4422 {
4423 	lockdep_assert_held(&cinode->open_file_lock);
4424 	server->ops->set_oplock_level(cinode, oplock, 0, NULL);
4425 }
4426 
4427 static void
4428 smb21_set_oplock_level(struct cifsInodeInfo *cinode, __u32 oplock,
4429 		       __u16 epoch, bool *purge_cache);
4430 
4431 static void
4432 smb3_downgrade_oplock(struct TCP_Server_Info *server,
4433 		       struct cifsInodeInfo *cinode, __u32 oplock,
4434 		       __u16 epoch, bool *purge_cache)
4435 {
4436 	unsigned int old_state = cinode->oplock;
4437 	__u16 old_epoch = cinode->epoch;
4438 	unsigned int new_state;
4439 
4440 	if (epoch > old_epoch) {
4441 		smb21_set_oplock_level(cinode, oplock, 0, NULL);
4442 		cinode->epoch = epoch;
4443 	}
4444 
4445 	new_state = cinode->oplock;
4446 	*purge_cache = false;
4447 
4448 	if ((old_state & CIFS_CACHE_READ_FLG) != 0 &&
4449 	    (new_state & CIFS_CACHE_READ_FLG) == 0)
4450 		*purge_cache = true;
4451 	else if (old_state == new_state && (epoch - old_epoch > 1))
4452 		*purge_cache = true;
4453 }
4454 
4455 static void
4456 smb2_set_oplock_level(struct cifsInodeInfo *cinode, __u32 oplock,
4457 		      __u16 epoch, bool *purge_cache)
4458 {
4459 	oplock &= 0xFF;
4460 	cinode->lease_granted = false;
4461 	if (oplock == SMB2_OPLOCK_LEVEL_NOCHANGE)
4462 		return;
4463 	if (oplock == SMB2_OPLOCK_LEVEL_BATCH) {
4464 		WRITE_ONCE(cinode->oplock, CIFS_CACHE_RHW_FLG);
4465 		cifs_dbg(FYI, "Batch Oplock granted on inode %p\n",
4466 			 &cinode->netfs.inode);
4467 	} else if (oplock == SMB2_OPLOCK_LEVEL_EXCLUSIVE) {
4468 		WRITE_ONCE(cinode->oplock, CIFS_CACHE_RW_FLG);
4469 		cifs_dbg(FYI, "Exclusive Oplock granted on inode %p\n",
4470 			 &cinode->netfs.inode);
4471 	} else if (oplock == SMB2_OPLOCK_LEVEL_II) {
4472 		WRITE_ONCE(cinode->oplock, CIFS_CACHE_READ_FLG);
4473 		cifs_dbg(FYI, "Level II Oplock granted on inode %p\n",
4474 			 &cinode->netfs.inode);
4475 	} else
4476 		WRITE_ONCE(cinode->oplock, 0);
4477 }
4478 
4479 static void
4480 smb21_set_oplock_level(struct cifsInodeInfo *cinode, __u32 oplock,
4481 		       __u16 epoch, bool *purge_cache)
4482 {
4483 	char message[5] = {0};
4484 	unsigned int new_oplock = 0;
4485 
4486 	oplock &= 0xFF;
4487 	cinode->lease_granted = true;
4488 	if (oplock == SMB2_OPLOCK_LEVEL_NOCHANGE)
4489 		return;
4490 
4491 	/* Check if the server granted an oplock rather than a lease */
4492 	if (oplock & SMB2_OPLOCK_LEVEL_EXCLUSIVE)
4493 		return smb2_set_oplock_level(cinode, oplock, epoch,
4494 					     purge_cache);
4495 
4496 	if (oplock & SMB2_LEASE_READ_CACHING_HE) {
4497 		new_oplock |= CIFS_CACHE_READ_FLG;
4498 		strcat(message, "R");
4499 	}
4500 	if (oplock & SMB2_LEASE_HANDLE_CACHING_HE) {
4501 		new_oplock |= CIFS_CACHE_HANDLE_FLG;
4502 		strcat(message, "H");
4503 	}
4504 	if (oplock & SMB2_LEASE_WRITE_CACHING_HE) {
4505 		new_oplock |= CIFS_CACHE_WRITE_FLG;
4506 		strcat(message, "W");
4507 	}
4508 	if (!new_oplock)
4509 		strscpy(message, "None");
4510 
4511 	WRITE_ONCE(cinode->oplock, new_oplock);
4512 	cifs_dbg(FYI, "%s Lease granted on inode %p\n", message,
4513 		 &cinode->netfs.inode);
4514 }
4515 
4516 static void
4517 smb3_set_oplock_level(struct cifsInodeInfo *cinode, __u32 oplock,
4518 		      __u16 epoch, bool *purge_cache)
4519 {
4520 	unsigned int old_oplock = READ_ONCE(cinode->oplock);
4521 	unsigned int new_oplock;
4522 
4523 	smb21_set_oplock_level(cinode, oplock, epoch, purge_cache);
4524 	new_oplock = READ_ONCE(cinode->oplock);
4525 
4526 	if (purge_cache) {
4527 		*purge_cache = false;
4528 		if (old_oplock == CIFS_CACHE_READ_FLG) {
4529 			if (new_oplock == CIFS_CACHE_READ_FLG &&
4530 			    (epoch - cinode->epoch > 0))
4531 				*purge_cache = true;
4532 			else if (new_oplock == CIFS_CACHE_RH_FLG &&
4533 				 (epoch - cinode->epoch > 1))
4534 				*purge_cache = true;
4535 			else if (new_oplock == CIFS_CACHE_RHW_FLG &&
4536 				 (epoch - cinode->epoch > 1))
4537 				*purge_cache = true;
4538 			else if (new_oplock == 0 &&
4539 				 (epoch - cinode->epoch > 0))
4540 				*purge_cache = true;
4541 		} else if (old_oplock == CIFS_CACHE_RH_FLG) {
4542 			if (new_oplock == CIFS_CACHE_RH_FLG &&
4543 			    (epoch - cinode->epoch > 0))
4544 				*purge_cache = true;
4545 			else if (new_oplock == CIFS_CACHE_RHW_FLG &&
4546 				 (epoch - cinode->epoch > 1))
4547 				*purge_cache = true;
4548 		}
4549 		cinode->epoch = epoch;
4550 	}
4551 }
4552 
4553 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
4554 static bool
4555 smb2_is_read_op(__u32 oplock)
4556 {
4557 	return oplock == SMB2_OPLOCK_LEVEL_II;
4558 }
4559 #endif /* CIFS_ALLOW_INSECURE_LEGACY */
4560 
4561 static bool
4562 smb21_is_read_op(__u32 oplock)
4563 {
4564 	return (oplock & SMB2_LEASE_READ_CACHING_HE) &&
4565 	       !(oplock & SMB2_LEASE_WRITE_CACHING_HE);
4566 }
4567 
4568 static __le32
4569 map_oplock_to_lease(u8 oplock)
4570 {
4571 	if (oplock == SMB2_OPLOCK_LEVEL_EXCLUSIVE)
4572 		return SMB2_LEASE_WRITE_CACHING_LE | SMB2_LEASE_READ_CACHING_LE;
4573 	else if (oplock == SMB2_OPLOCK_LEVEL_II)
4574 		return SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE;
4575 	else if (oplock == SMB2_OPLOCK_LEVEL_BATCH)
4576 		return SMB2_LEASE_HANDLE_CACHING_LE | SMB2_LEASE_READ_CACHING_LE |
4577 		       SMB2_LEASE_WRITE_CACHING_LE;
4578 	return 0;
4579 }
4580 
4581 static char *
4582 smb2_create_lease_buf(u8 *lease_key, u8 oplock, u8 *parent_lease_key, __le32 flags)
4583 {
4584 	struct create_lease *buf;
4585 
4586 	buf = kzalloc_obj(struct create_lease);
4587 	if (!buf)
4588 		return NULL;
4589 
4590 	memcpy(&buf->lcontext.LeaseKey, lease_key, SMB2_LEASE_KEY_SIZE);
4591 	buf->lcontext.LeaseState = map_oplock_to_lease(oplock);
4592 
4593 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
4594 					(struct create_lease, lcontext));
4595 	buf->ccontext.DataLength = cpu_to_le32(sizeof(struct lease_context));
4596 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
4597 				(struct create_lease, Name));
4598 	buf->ccontext.NameLength = cpu_to_le16(4);
4599 	/* SMB2_CREATE_REQUEST_LEASE is "RqLs" */
4600 	buf->Name[0] = 'R';
4601 	buf->Name[1] = 'q';
4602 	buf->Name[2] = 'L';
4603 	buf->Name[3] = 's';
4604 	return (char *)buf;
4605 }
4606 
4607 static char *
4608 smb3_create_lease_buf(u8 *lease_key, u8 oplock, u8 *parent_lease_key, __le32 flags)
4609 {
4610 	struct create_lease_v2 *buf;
4611 
4612 	buf = kzalloc_obj(struct create_lease_v2);
4613 	if (!buf)
4614 		return NULL;
4615 
4616 	memcpy(&buf->lcontext.LeaseKey, lease_key, SMB2_LEASE_KEY_SIZE);
4617 	buf->lcontext.LeaseState = map_oplock_to_lease(oplock);
4618 	buf->lcontext.LeaseFlags = flags;
4619 	if (flags & SMB2_LEASE_FLAG_PARENT_LEASE_KEY_SET_LE)
4620 		memcpy(&buf->lcontext.ParentLeaseKey, parent_lease_key, SMB2_LEASE_KEY_SIZE);
4621 
4622 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
4623 					(struct create_lease_v2, lcontext));
4624 	buf->ccontext.DataLength = cpu_to_le32(sizeof(struct lease_context_v2));
4625 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
4626 				(struct create_lease_v2, Name));
4627 	buf->ccontext.NameLength = cpu_to_le16(4);
4628 	/* SMB2_CREATE_REQUEST_LEASE is "RqLs" */
4629 	buf->Name[0] = 'R';
4630 	buf->Name[1] = 'q';
4631 	buf->Name[2] = 'L';
4632 	buf->Name[3] = 's';
4633 	return (char *)buf;
4634 }
4635 
4636 static __u8
4637 smb2_parse_lease_buf(void *buf, __u16 *epoch, char *lease_key)
4638 {
4639 	struct create_context *cc = buf;
4640 	struct lease_context lc;
4641 
4642 	*epoch = 0; /* not used */
4643 	if (le32_to_cpu(cc->DataLength) != sizeof(lc))
4644 		return 0;
4645 
4646 	memcpy(&lc, (u8 *)cc + le16_to_cpu(cc->DataOffset), sizeof(lc));
4647 	if (lc.LeaseFlags & SMB2_LEASE_FLAG_BREAK_IN_PROGRESS_LE)
4648 		return SMB2_OPLOCK_LEVEL_NOCHANGE;
4649 	return le32_to_cpu(lc.LeaseState);
4650 }
4651 
4652 static __u8
4653 smb3_parse_lease_buf(void *buf, __u16 *epoch, char *lease_key)
4654 {
4655 	struct create_context *cc = buf;
4656 	struct lease_context_v2 lc;
4657 
4658 	if (le32_to_cpu(cc->DataLength) != sizeof(lc)) {
4659 		*epoch = 0;
4660 		return 0;
4661 	}
4662 
4663 	memcpy(&lc, (u8 *)cc + le16_to_cpu(cc->DataOffset), sizeof(lc));
4664 	*epoch = le16_to_cpu(lc.Epoch);
4665 	if (lc.LeaseFlags & SMB2_LEASE_FLAG_BREAK_IN_PROGRESS_LE)
4666 		return SMB2_OPLOCK_LEVEL_NOCHANGE;
4667 	if (lease_key)
4668 		memcpy(lease_key, lc.LeaseKey, SMB2_LEASE_KEY_SIZE);
4669 	return le32_to_cpu(lc.LeaseState);
4670 }
4671 
4672 static unsigned int
4673 smb2_wp_retry_size(struct inode *inode)
4674 {
4675 	return min_t(unsigned int, CIFS_SB(inode->i_sb)->ctx->wsize,
4676 		     SMB2_MAX_BUFFER_SIZE);
4677 }
4678 
4679 static bool
4680 smb2_dir_needs_close(struct cifsFileInfo *cfile)
4681 {
4682 	return !cfile->invalidHandle;
4683 }
4684 
4685 static void
4686 fill_transform_hdr(struct smb2_transform_hdr *tr_hdr, unsigned int orig_len,
4687 		   struct smb_rqst *old_rq, __le16 cipher_type)
4688 {
4689 	struct smb2_hdr *shdr =
4690 			(struct smb2_hdr *)old_rq->rq_iov[0].iov_base;
4691 
4692 	memset(tr_hdr, 0, sizeof(struct smb2_transform_hdr));
4693 	tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
4694 	tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
4695 	tr_hdr->Flags = cpu_to_le16(0x01);
4696 	if ((cipher_type == SMB2_ENCRYPTION_AES128_GCM) ||
4697 	    (cipher_type == SMB2_ENCRYPTION_AES256_GCM))
4698 		get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
4699 	else
4700 		get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
4701 	memcpy(&tr_hdr->SessionId, &shdr->SessionId, 8);
4702 }
4703 
4704 static void *smb2_aead_req_alloc(struct crypto_aead *tfm, const struct smb_rqst *rqst,
4705 				 int num_rqst, const u8 *sig, u8 **iv,
4706 				 struct aead_request **req, struct sg_table *sgt,
4707 				 unsigned int *num_sgs)
4708 {
4709 	unsigned int req_size = sizeof(**req) + crypto_aead_reqsize(tfm);
4710 	unsigned int iv_size = crypto_aead_ivsize(tfm);
4711 	unsigned int len;
4712 	int ret;
4713 	u8 *p;
4714 
4715 	ret = cifs_get_num_sgs(rqst, num_rqst, sig);
4716 	if (ret < 0)
4717 		return ERR_PTR(ret);
4718 	*num_sgs = ret;
4719 
4720 	len = iv_size;
4721 	len += crypto_aead_alignmask(tfm) & ~(crypto_tfm_ctx_alignment() - 1);
4722 	len = ALIGN(len, crypto_tfm_ctx_alignment());
4723 	len += req_size;
4724 	len = ALIGN(len, __alignof__(struct scatterlist));
4725 	len += array_size(*num_sgs, sizeof(struct scatterlist));
4726 
4727 	p = kzalloc(len, GFP_NOFS);
4728 	if (!p)
4729 		return ERR_PTR(-ENOMEM);
4730 
4731 	*iv = (u8 *)PTR_ALIGN(p, crypto_aead_alignmask(tfm) + 1);
4732 	*req = (struct aead_request *)PTR_ALIGN(*iv + iv_size,
4733 						crypto_tfm_ctx_alignment());
4734 	sgt->sgl = (struct scatterlist *)PTR_ALIGN((u8 *)*req + req_size,
4735 						   __alignof__(struct scatterlist));
4736 	return p;
4737 }
4738 
4739 static void *smb2_get_aead_req(struct crypto_aead *tfm, struct smb_rqst *rqst,
4740 			       int num_rqst, const u8 *sig, u8 **iv,
4741 			       struct aead_request **req, struct scatterlist **sgl)
4742 {
4743 	struct sg_table sgtable = {};
4744 	unsigned int skip, num_sgs, i, j;
4745 	ssize_t rc;
4746 	void *p;
4747 
4748 	p = smb2_aead_req_alloc(tfm, rqst, num_rqst, sig, iv, req, &sgtable, &num_sgs);
4749 	if (IS_ERR(p))
4750 		return ERR_CAST(p);
4751 
4752 	sg_init_marker(sgtable.sgl, num_sgs);
4753 
4754 	/*
4755 	 * The first rqst has a transform header where the
4756 	 * first 20 bytes are not part of the encrypted blob.
4757 	 */
4758 	skip = 20;
4759 
4760 	for (i = 0; i < num_rqst; i++) {
4761 		struct iov_iter *iter = &rqst[i].rq_iter;
4762 		size_t count = iov_iter_count(iter);
4763 
4764 		for (j = 0; j < rqst[i].rq_nvec; j++) {
4765 			cifs_sg_set_buf(&sgtable,
4766 					rqst[i].rq_iov[j].iov_base + skip,
4767 					rqst[i].rq_iov[j].iov_len - skip);
4768 
4769 			/* See the above comment on the 'skip' assignment */
4770 			skip = 0;
4771 		}
4772 		sgtable.orig_nents = sgtable.nents;
4773 
4774 		rc = extract_iter_to_sg(iter, count, &sgtable,
4775 					num_sgs - sgtable.nents, 0);
4776 		iov_iter_revert(iter, rc);
4777 		sgtable.orig_nents = sgtable.nents;
4778 	}
4779 
4780 	cifs_sg_set_buf(&sgtable, sig, SMB2_SIGNATURE_SIZE);
4781 	sg_mark_end(&sgtable.sgl[sgtable.nents - 1]);
4782 	*sgl = sgtable.sgl;
4783 	return p;
4784 }
4785 
4786 static int
4787 smb2_get_enc_key(struct TCP_Server_Info *server, __u64 ses_id, int enc, u8 *key)
4788 {
4789 	struct TCP_Server_Info *pserver;
4790 	struct cifs_ses *ses;
4791 	u8 *ses_enc_key;
4792 
4793 	/* If server is a channel, select the primary channel */
4794 	pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
4795 
4796 	spin_lock(&cifs_tcp_ses_lock);
4797 	list_for_each_entry(ses, &pserver->smb_ses_list, smb_ses_list) {
4798 		if (ses->Suid == ses_id) {
4799 			spin_lock(&ses->ses_lock);
4800 			ses_enc_key = enc ? ses->smb3encryptionkey :
4801 				ses->smb3decryptionkey;
4802 			memcpy(key, ses_enc_key, SMB3_ENC_DEC_KEY_SIZE);
4803 			spin_unlock(&ses->ses_lock);
4804 			spin_unlock(&cifs_tcp_ses_lock);
4805 			return 0;
4806 		}
4807 	}
4808 	spin_unlock(&cifs_tcp_ses_lock);
4809 
4810 	trace_smb3_ses_not_found(ses_id);
4811 
4812 	return -EAGAIN;
4813 }
4814 /*
4815  * Encrypt or decrypt @rqst message. @rqst[0] has the following format:
4816  * iov[0]   - transform header (associate data),
4817  * iov[1-N] - SMB2 header and pages - data to encrypt.
4818  * On success return encrypted data in iov[1-N] and pages, leave iov[0]
4819  * untouched.
4820  */
4821 static int
4822 crypt_message(struct TCP_Server_Info *server, int num_rqst,
4823 	      struct smb_rqst *rqst, int enc, struct crypto_aead *tfm)
4824 {
4825 	struct smb2_transform_hdr *tr_hdr =
4826 		(struct smb2_transform_hdr *)rqst[0].rq_iov[0].iov_base;
4827 	unsigned int assoc_data_len = sizeof(struct smb2_transform_hdr) - 20;
4828 	int rc = 0;
4829 	struct scatterlist *sg;
4830 	u8 sign[SMB2_SIGNATURE_SIZE] = {};
4831 	u8 key[SMB3_ENC_DEC_KEY_SIZE];
4832 	struct aead_request *req;
4833 	u8 *iv;
4834 	DECLARE_CRYPTO_WAIT(wait);
4835 	unsigned int crypt_len = le32_to_cpu(tr_hdr->OriginalMessageSize);
4836 	void *creq;
4837 
4838 	rc = smb2_get_enc_key(server, le64_to_cpu(tr_hdr->SessionId), enc, key);
4839 	if (rc) {
4840 		cifs_server_dbg(FYI, "%s: Could not get %scryption key. sid: 0x%llx\n", __func__,
4841 			 enc ? "en" : "de", le64_to_cpu(tr_hdr->SessionId));
4842 		return rc;
4843 	}
4844 
4845 	if ((server->cipher_type == SMB2_ENCRYPTION_AES256_CCM) ||
4846 		(server->cipher_type == SMB2_ENCRYPTION_AES256_GCM))
4847 		rc = crypto_aead_setkey(tfm, key, SMB3_GCM256_CRYPTKEY_SIZE);
4848 	else
4849 		rc = crypto_aead_setkey(tfm, key, SMB3_GCM128_CRYPTKEY_SIZE);
4850 	memzero_explicit(key, sizeof(key));
4851 	if (rc) {
4852 		cifs_server_dbg(VFS, "%s: Failed to set aead key %d\n", __func__, rc);
4853 		return rc;
4854 	}
4855 
4856 	rc = crypto_aead_setauthsize(tfm, SMB2_SIGNATURE_SIZE);
4857 	if (rc) {
4858 		cifs_server_dbg(VFS, "%s: Failed to set authsize %d\n", __func__, rc);
4859 		return rc;
4860 	}
4861 
4862 	creq = smb2_get_aead_req(tfm, rqst, num_rqst, sign, &iv, &req, &sg);
4863 	if (IS_ERR(creq))
4864 		return PTR_ERR(creq);
4865 
4866 	if (!enc) {
4867 		memcpy(sign, &tr_hdr->Signature, SMB2_SIGNATURE_SIZE);
4868 		crypt_len += SMB2_SIGNATURE_SIZE;
4869 	}
4870 
4871 	if ((server->cipher_type == SMB2_ENCRYPTION_AES128_GCM) ||
4872 	    (server->cipher_type == SMB2_ENCRYPTION_AES256_GCM))
4873 		memcpy(iv, (char *)tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
4874 	else {
4875 		iv[0] = 3;
4876 		memcpy(iv + 1, (char *)tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
4877 	}
4878 
4879 	aead_request_set_tfm(req, tfm);
4880 	aead_request_set_crypt(req, sg, sg, crypt_len, iv);
4881 	aead_request_set_ad(req, assoc_data_len);
4882 
4883 	aead_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
4884 				  crypto_req_done, &wait);
4885 
4886 	rc = crypto_wait_req(enc ? crypto_aead_encrypt(req)
4887 				: crypto_aead_decrypt(req), &wait);
4888 
4889 	if (!rc && enc)
4890 		memcpy(&tr_hdr->Signature, sign, SMB2_SIGNATURE_SIZE);
4891 
4892 	kfree_sensitive(creq);
4893 	return rc;
4894 }
4895 
4896 /*
4897  * Copy data from an iterator to the folios in a folio queue buffer.
4898  */
4899 static bool cifs_copy_iter_to_folioq(struct iov_iter *iter, size_t size,
4900 				     struct folio_queue *buffer)
4901 {
4902 	for (; buffer; buffer = buffer->next) {
4903 		for (int s = 0; s < folioq_count(buffer); s++) {
4904 			struct folio *folio = folioq_folio(buffer, s);
4905 			size_t part = folioq_folio_size(buffer, s);
4906 
4907 			part = umin(part, size);
4908 
4909 			if (copy_folio_from_iter(folio, 0, part, iter) != part)
4910 				return false;
4911 			size -= part;
4912 		}
4913 	}
4914 	return true;
4915 }
4916 
4917 void
4918 smb3_free_compound_rqst(int num_rqst, struct smb_rqst *rqst)
4919 {
4920 	for (int i = 0; i < num_rqst; i++)
4921 		netfs_free_folioq_buffer(rqst[i].rq_buffer);
4922 }
4923 
4924 /*
4925  * This function will initialize new_rq and encrypt the content.
4926  * The first entry, new_rq[0], only contains a single iov which contains
4927  * a smb2_transform_hdr and is pre-allocated by the caller.
4928  * This function then populates new_rq[1+] with the content from olq_rq[0+].
4929  *
4930  * The end result is an array of smb_rqst structures where the first structure
4931  * only contains a single iov for the transform header which we then can pass
4932  * to crypt_message().
4933  *
4934  * new_rq[0].rq_iov[0] :  smb2_transform_hdr pre-allocated by the caller
4935  * new_rq[1+].rq_iov[*] == old_rq[0+].rq_iov[*] : SMB2/3 requests
4936  */
4937 static int
4938 smb3_init_transform_rq(struct TCP_Server_Info *server, int num_rqst,
4939 		       struct smb_rqst *new_rq, struct smb_rqst *old_rq)
4940 {
4941 	struct smb2_transform_hdr *tr_hdr = new_rq[0].rq_iov[0].iov_base;
4942 	unsigned int orig_len = 0;
4943 	int rc = -ENOMEM;
4944 
4945 	for (int i = 1; i < num_rqst; i++) {
4946 		struct smb_rqst *old = &old_rq[i - 1];
4947 		struct smb_rqst *new = &new_rq[i];
4948 		struct folio_queue *buffer = NULL;
4949 		size_t size = iov_iter_count(&old->rq_iter);
4950 
4951 		orig_len += smb_rqst_len(server, old);
4952 		new->rq_iov = old->rq_iov;
4953 		new->rq_nvec = old->rq_nvec;
4954 
4955 		if (size > 0) {
4956 			size_t cur_size = 0;
4957 			rc = netfs_alloc_folioq_buffer(NULL, &buffer, &cur_size,
4958 						       size, GFP_NOFS);
4959 			new->rq_buffer = buffer;
4960 			if (rc < 0)
4961 				goto err_free;
4962 
4963 			iov_iter_folio_queue(&new->rq_iter, ITER_SOURCE,
4964 					     buffer, 0, 0, size);
4965 
4966 			if (!cifs_copy_iter_to_folioq(&old->rq_iter, size, buffer)) {
4967 				rc = smb_EIO1(smb_eio_trace_tx_copy_iter_to_buf, size);
4968 				goto err_free;
4969 			}
4970 		}
4971 	}
4972 
4973 	/* fill the 1st iov with a transform header */
4974 	fill_transform_hdr(tr_hdr, orig_len, old_rq, server->cipher_type);
4975 
4976 	rc = crypt_message(server, num_rqst, new_rq, 1, server->secmech.enc);
4977 	cifs_dbg(FYI, "Encrypt message returned %d\n", rc);
4978 	if (rc)
4979 		goto err_free;
4980 
4981 	return rc;
4982 
4983 err_free:
4984 	smb3_free_compound_rqst(num_rqst - 1, &new_rq[1]);
4985 	return rc;
4986 }
4987 
4988 static int
4989 smb3_is_transform_hdr(void *buf)
4990 {
4991 	struct smb2_transform_hdr *trhdr = buf;
4992 
4993 	return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
4994 }
4995 
4996 static int
4997 decrypt_raw_data(struct TCP_Server_Info *server, char *buf,
4998 		 unsigned int buf_data_size, struct iov_iter *iter,
4999 		 bool is_offloaded)
5000 {
5001 	struct crypto_aead *tfm;
5002 	struct smb_rqst rqst = {NULL};
5003 	struct kvec iov[2];
5004 	size_t iter_size = 0;
5005 	int rc;
5006 
5007 	iov[0].iov_base = buf;
5008 	iov[0].iov_len = sizeof(struct smb2_transform_hdr);
5009 	iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr);
5010 	iov[1].iov_len = buf_data_size;
5011 
5012 	rqst.rq_iov = iov;
5013 	rqst.rq_nvec = 2;
5014 	if (iter) {
5015 		rqst.rq_iter = *iter;
5016 		iter_size = iov_iter_count(iter);
5017 	}
5018 
5019 	if (is_offloaded) {
5020 		if ((server->cipher_type == SMB2_ENCRYPTION_AES128_GCM) ||
5021 		    (server->cipher_type == SMB2_ENCRYPTION_AES256_GCM))
5022 			tfm = crypto_alloc_aead("gcm(aes)", 0, 0);
5023 		else
5024 			tfm = crypto_alloc_aead("ccm(aes)", 0, 0);
5025 		if (IS_ERR(tfm)) {
5026 			rc = PTR_ERR(tfm);
5027 			cifs_server_dbg(VFS, "%s: Failed alloc decrypt TFM, rc=%d\n", __func__, rc);
5028 
5029 			return rc;
5030 		}
5031 	} else {
5032 		rc = smb3_crypto_aead_allocate(server);
5033 		if (unlikely(rc))
5034 			return rc;
5035 		tfm = server->secmech.dec;
5036 	}
5037 
5038 	rc = crypt_message(server, 1, &rqst, 0, tfm);
5039 	cifs_dbg(FYI, "Decrypt message returned %d\n", rc);
5040 
5041 	if (is_offloaded)
5042 		crypto_free_aead(tfm);
5043 
5044 	if (rc)
5045 		return rc;
5046 
5047 	memmove(buf, iov[1].iov_base, buf_data_size);
5048 
5049 	if (!is_offloaded)
5050 		server->total_read = buf_data_size + iter_size;
5051 
5052 	return rc;
5053 }
5054 
5055 static int
5056 cifs_copy_folioq_to_iter(struct folio_queue *folioq, size_t data_size,
5057 			 size_t skip, struct iov_iter *iter)
5058 {
5059 	for (; folioq; folioq = folioq->next) {
5060 		for (int s = 0; s < folioq_count(folioq); s++) {
5061 			struct folio *folio;
5062 			size_t fsize, n, len;
5063 
5064 			if (data_size == 0)
5065 				return 0;
5066 
5067 			folio = folioq_folio(folioq, s);
5068 			fsize = folio_size(folio);
5069 			len = umin(fsize - skip, data_size);
5070 
5071 			n = copy_folio_to_iter(folio, skip, len, iter);
5072 			if (n != len) {
5073 				cifs_dbg(VFS, "%s: something went wrong\n", __func__);
5074 				return smb_EIO2(smb_eio_trace_rx_copy_to_iter,
5075 						n, len);
5076 			}
5077 			data_size -= n;
5078 			skip = 0;
5079 		}
5080 	}
5081 
5082 	if (data_size != 0) {
5083 		cifs_dbg(VFS, "%s: short copy, %zu bytes missing\n",
5084 			 __func__, data_size);
5085 		return smb_EIO2(smb_eio_trace_rx_copy_to_iter, 0, data_size);
5086 	}
5087 
5088 	return 0;
5089 }
5090 
5091 static int
5092 handle_read_data(struct TCP_Server_Info *server, struct mid_q_entry *mid,
5093 		 char *buf, unsigned int buf_len, struct folio_queue *buffer,
5094 		 unsigned int buffer_len, bool is_offloaded)
5095 {
5096 	unsigned int data_offset;
5097 	unsigned int data_len;
5098 	unsigned int end_off;
5099 	unsigned int cur_off;
5100 	unsigned int cur_page_idx;
5101 	unsigned int pad_len;
5102 	struct cifs_io_subrequest *rdata = mid->callback_data;
5103 	struct smb2_hdr *shdr = (struct smb2_hdr *)buf;
5104 	size_t copied;
5105 	bool use_rdma_mr = false;
5106 
5107 	if (shdr->Command != SMB2_READ) {
5108 		cifs_server_dbg(VFS, "only big read responses are supported\n");
5109 		return -EOPNOTSUPP;
5110 	}
5111 
5112 	if (server->ops->is_session_expired &&
5113 	    server->ops->is_session_expired(buf)) {
5114 		if (!is_offloaded)
5115 			cifs_reconnect(server, true);
5116 		return -1;
5117 	}
5118 
5119 	if (server->ops->is_status_pending &&
5120 			server->ops->is_status_pending(buf, server))
5121 		return -1;
5122 
5123 	/* set up first two iov to get credits */
5124 	rdata->iov[0].iov_base = buf;
5125 	rdata->iov[0].iov_len = 0;
5126 	rdata->iov[1].iov_base = buf;
5127 	rdata->iov[1].iov_len =
5128 		min_t(unsigned int, buf_len, server->vals->read_rsp_size);
5129 	cifs_dbg(FYI, "0: iov_base=%p iov_len=%zu\n",
5130 		 rdata->iov[0].iov_base, rdata->iov[0].iov_len);
5131 	cifs_dbg(FYI, "1: iov_base=%p iov_len=%zu\n",
5132 		 rdata->iov[1].iov_base, rdata->iov[1].iov_len);
5133 
5134 	rdata->result = server->ops->map_error(buf, true);
5135 	if (rdata->result != 0) {
5136 		cifs_dbg(FYI, "%s: server returned error %d\n",
5137 			 __func__, rdata->result);
5138 		/* normal error on read response */
5139 		if (is_offloaded)
5140 			mid->mid_state = MID_RESPONSE_RECEIVED;
5141 		else
5142 			dequeue_mid(server, mid, false);
5143 		return 0;
5144 	}
5145 
5146 	data_offset = server->ops->read_data_offset(buf);
5147 #ifdef CONFIG_CIFS_SMB_DIRECT
5148 	use_rdma_mr = rdata->mr;
5149 #endif
5150 	data_len = server->ops->read_data_length(buf, use_rdma_mr);
5151 
5152 	if (data_offset < server->vals->read_rsp_size) {
5153 		/*
5154 		 * win2k8 sometimes sends an offset of 0 when the read
5155 		 * is beyond the EOF. Treat it as if the data starts just after
5156 		 * the header.
5157 		 */
5158 		cifs_dbg(FYI, "%s: data offset (%u) inside read response header\n",
5159 			 __func__, data_offset);
5160 		data_offset = server->vals->read_rsp_size;
5161 	} else if (data_offset > MAX_CIFS_SMALL_BUFFER_SIZE) {
5162 		/* data_offset is beyond the end of smallbuf */
5163 		cifs_dbg(FYI, "%s: data offset (%u) beyond end of smallbuf\n",
5164 			 __func__, data_offset);
5165 		rdata->result = smb_EIO1(smb_eio_trace_rx_overlong, data_offset);
5166 		if (is_offloaded)
5167 			mid->mid_state = MID_RESPONSE_MALFORMED;
5168 		else
5169 			dequeue_mid(server, mid, rdata->result);
5170 		return 0;
5171 	}
5172 
5173 	pad_len = data_offset - server->vals->read_rsp_size;
5174 
5175 	if (buf_len <= data_offset) {
5176 		/* read response payload is in pages */
5177 		cur_page_idx = pad_len / PAGE_SIZE;
5178 		cur_off = pad_len % PAGE_SIZE;
5179 
5180 		if (cur_page_idx != 0) {
5181 			/* data offset is beyond the 1st page of response */
5182 			cifs_dbg(FYI, "%s: data offset (%u) beyond 1st page of response\n",
5183 				 __func__, data_offset);
5184 			rdata->result = smb_EIO1(smb_eio_trace_rx_overpage, data_offset);
5185 			if (is_offloaded)
5186 				mid->mid_state = MID_RESPONSE_MALFORMED;
5187 			else
5188 				dequeue_mid(server, mid, rdata->result);
5189 			return 0;
5190 		}
5191 
5192 		if (data_len > buffer_len - pad_len) {
5193 			/* data_len is corrupt -- discard frame */
5194 			rdata->result = smb_EIO1(smb_eio_trace_rx_bad_datalen, data_len);
5195 			if (is_offloaded)
5196 				mid->mid_state = MID_RESPONSE_MALFORMED;
5197 			else
5198 				dequeue_mid(server, mid, rdata->result);
5199 			return 0;
5200 		}
5201 
5202 		/* Copy the data to the output I/O iterator. */
5203 		rdata->result = cifs_copy_folioq_to_iter(buffer, data_len,
5204 							 cur_off, &rdata->subreq.io_iter);
5205 		if (rdata->result != 0) {
5206 			if (is_offloaded)
5207 				mid->mid_state = MID_RESPONSE_MALFORMED;
5208 			else
5209 				dequeue_mid(server, mid, rdata->result);
5210 			return 0;
5211 		}
5212 		rdata->got_bytes = data_len;
5213 
5214 	} else if (!check_add_overflow(data_offset, data_len, &end_off) &&
5215 		   buf_len >= end_off) {
5216 		/* read response payload is in buf */
5217 		WARN_ONCE(buffer, "read data can be either in buf or in buffer");
5218 		copied = copy_to_iter(buf + data_offset, data_len, &rdata->subreq.io_iter);
5219 		if (copied == 0)
5220 			return smb_EIO2(smb_eio_trace_rx_copy_to_iter, copied, data_len);
5221 		rdata->got_bytes = copied;
5222 	} else {
5223 		/* read response payload cannot be in both buf and pages */
5224 		WARN_ONCE(1, "buf can not contain only a part of read data");
5225 		rdata->result = smb_EIO(smb_eio_trace_rx_both_buf);
5226 		if (is_offloaded)
5227 			mid->mid_state = MID_RESPONSE_MALFORMED;
5228 		else
5229 			dequeue_mid(server, mid, rdata->result);
5230 		return 0;
5231 	}
5232 
5233 	if (is_offloaded)
5234 		mid->mid_state = MID_RESPONSE_RECEIVED;
5235 	else
5236 		dequeue_mid(server, mid, false);
5237 	return 0;
5238 }
5239 
5240 struct smb2_decrypt_work {
5241 	struct work_struct decrypt;
5242 	struct TCP_Server_Info *server;
5243 	struct folio_queue *buffer;
5244 	char *buf;
5245 	unsigned int len;
5246 };
5247 
5248 
5249 static void smb2_decrypt_offload(struct work_struct *work)
5250 {
5251 	struct smb2_decrypt_work *dw = container_of(work,
5252 				struct smb2_decrypt_work, decrypt);
5253 	int rc;
5254 	struct mid_q_entry *mid;
5255 	struct iov_iter iter;
5256 
5257 	iov_iter_folio_queue(&iter, ITER_DEST, dw->buffer, 0, 0, dw->len);
5258 	rc = decrypt_raw_data(dw->server, dw->buf, dw->server->vals->read_rsp_size,
5259 			      &iter, true);
5260 	if (rc) {
5261 		cifs_dbg(VFS, "error decrypting rc=%d\n", rc);
5262 		goto free_pages;
5263 	}
5264 
5265 	dw->server->lstrp = jiffies;
5266 	mid = smb2_find_dequeue_mid(dw->server, dw->buf);
5267 	if (mid == NULL) {
5268 		cifs_dbg(FYI, "mid not found\n");
5269 		smb2_add_credits_from_hdr(dw->buf, dw->server);
5270 	} else {
5271 		mid->decrypted = true;
5272 		rc = handle_read_data(dw->server, mid, dw->buf,
5273 				      dw->server->vals->read_rsp_size,
5274 				      dw->buffer, dw->len,
5275 				      true);
5276 		if (rc >= 0) {
5277 #ifdef CONFIG_CIFS_STATS2
5278 			mid->when_received = jiffies;
5279 #endif
5280 			if (dw->server->ops->is_network_name_deleted)
5281 				dw->server->ops->is_network_name_deleted(dw->buf,
5282 									 dw->server);
5283 
5284 			mid_execute_callback(dw->server, mid);
5285 		} else {
5286 			spin_lock(&dw->server->srv_lock);
5287 			if (dw->server->tcpStatus == CifsNeedReconnect) {
5288 				spin_lock(&dw->server->mid_queue_lock);
5289 				mid->mid_state = MID_RETRY_NEEDED;
5290 				spin_unlock(&dw->server->mid_queue_lock);
5291 				spin_unlock(&dw->server->srv_lock);
5292 				mid_execute_callback(dw->server, mid);
5293 			} else {
5294 				spin_lock(&dw->server->mid_queue_lock);
5295 				mid->mid_state = MID_REQUEST_SUBMITTED;
5296 				mid->deleted_from_q = false;
5297 				list_add_tail(&mid->qhead,
5298 					&dw->server->pending_mid_q);
5299 				spin_unlock(&dw->server->mid_queue_lock);
5300 				spin_unlock(&dw->server->srv_lock);
5301 			}
5302 		}
5303 		release_mid(dw->server, mid);
5304 	}
5305 
5306 free_pages:
5307 	netfs_free_folioq_buffer(dw->buffer);
5308 	cifs_small_buf_release(dw->buf);
5309 	kfree(dw);
5310 }
5311 
5312 
5313 static int
5314 receive_encrypted_read(struct TCP_Server_Info *server, struct mid_q_entry **mid,
5315 		       int *num_mids)
5316 {
5317 	char *buf = server->smallbuf;
5318 	struct smb2_transform_hdr *tr_hdr = (struct smb2_transform_hdr *)buf;
5319 	struct iov_iter iter;
5320 	unsigned int len;
5321 	unsigned int buflen = server->pdu_size;
5322 	int rc;
5323 	struct smb2_decrypt_work *dw;
5324 
5325 	dw = kzalloc_obj(struct smb2_decrypt_work);
5326 	if (!dw)
5327 		return -ENOMEM;
5328 	INIT_WORK(&dw->decrypt, smb2_decrypt_offload);
5329 	dw->server = server;
5330 
5331 	*num_mids = 1;
5332 	len = min_t(unsigned int, buflen, server->vals->read_rsp_size +
5333 		sizeof(struct smb2_transform_hdr)) - HEADER_SIZE(server) + 1;
5334 
5335 	rc = cifs_read_from_socket(server, buf + HEADER_SIZE(server) - 1, len);
5336 	if (rc < 0)
5337 		goto free_dw;
5338 	server->total_read += rc;
5339 
5340 	if (le32_to_cpu(tr_hdr->OriginalMessageSize) <
5341 	    server->vals->read_rsp_size) {
5342 		cifs_server_dbg(VFS, "OriginalMessageSize %u too small for read response (%zu)\n",
5343 			le32_to_cpu(tr_hdr->OriginalMessageSize),
5344 			server->vals->read_rsp_size);
5345 		rc = -EINVAL;
5346 		goto discard_data;
5347 	}
5348 	len = le32_to_cpu(tr_hdr->OriginalMessageSize) -
5349 		server->vals->read_rsp_size;
5350 	dw->len = len;
5351 	len = round_up(dw->len, PAGE_SIZE);
5352 
5353 	size_t cur_size = 0;
5354 	rc = netfs_alloc_folioq_buffer(NULL, &dw->buffer, &cur_size, len, GFP_NOFS);
5355 	if (rc < 0)
5356 		goto discard_data;
5357 
5358 	iov_iter_folio_queue(&iter, ITER_DEST, dw->buffer, 0, 0, len);
5359 
5360 	/* Read the data into the buffer and clear excess bufferage. */
5361 	rc = cifs_read_iter_from_socket(server, &iter, dw->len);
5362 	if (rc < 0)
5363 		goto discard_data;
5364 
5365 	server->total_read += rc;
5366 	if (rc < len) {
5367 		struct iov_iter tmp = iter;
5368 
5369 		iov_iter_advance(&tmp, rc);
5370 		iov_iter_zero(len - rc, &tmp);
5371 	}
5372 	iov_iter_truncate(&iter, dw->len);
5373 
5374 	rc = cifs_discard_remaining_data(server);
5375 	if (rc)
5376 		goto free_pages;
5377 
5378 	/*
5379 	 * For large reads, offload to different thread for better performance,
5380 	 * use more cores decrypting which can be expensive
5381 	 */
5382 
5383 	if ((server->min_offload) && (server->in_flight > 1) &&
5384 	    (server->pdu_size >= server->min_offload)) {
5385 		dw->buf = server->smallbuf;
5386 		server->smallbuf = (char *)cifs_small_buf_get();
5387 
5388 		queue_work(decrypt_wq, &dw->decrypt);
5389 		*num_mids = 0; /* worker thread takes care of finding mid */
5390 		return -1;
5391 	}
5392 
5393 	rc = decrypt_raw_data(server, buf, server->vals->read_rsp_size,
5394 			      &iter, false);
5395 	if (rc)
5396 		goto free_pages;
5397 
5398 	*mid = smb2_find_mid(server, buf);
5399 	if (*mid == NULL) {
5400 		cifs_dbg(FYI, "mid not found\n");
5401 		smb2_add_credits_from_hdr(buf, server);
5402 		rc = -1;
5403 	} else {
5404 		cifs_dbg(FYI, "mid found\n");
5405 		(*mid)->decrypted = true;
5406 		rc = handle_read_data(server, *mid, buf,
5407 				      server->vals->read_rsp_size,
5408 				      dw->buffer, dw->len, false);
5409 		if (rc >= 0) {
5410 			if (server->ops->is_network_name_deleted) {
5411 				server->ops->is_network_name_deleted(buf,
5412 								server);
5413 			}
5414 		}
5415 	}
5416 
5417 free_pages:
5418 	netfs_free_folioq_buffer(dw->buffer);
5419 free_dw:
5420 	kfree(dw);
5421 	return rc;
5422 discard_data:
5423 	cifs_discard_remaining_data(server);
5424 	goto free_pages;
5425 }
5426 
5427 static int
5428 receive_encrypted_standard(struct TCP_Server_Info *server,
5429 			   struct mid_q_entry **mids, char **bufs,
5430 			   int *num_mids)
5431 {
5432 	int ret, length;
5433 	char *buf = server->smallbuf;
5434 	struct smb2_hdr *shdr;
5435 	unsigned int pdu_length = server->pdu_size;
5436 	unsigned int buf_size;
5437 	unsigned int next_cmd;
5438 	struct mid_q_entry *mid_entry;
5439 	int next_is_large;
5440 	char *next_buffer = NULL;
5441 
5442 	*num_mids = 0;
5443 
5444 	/* switch to large buffer if too big for a small one */
5445 	if (pdu_length > MAX_CIFS_SMALL_BUFFER_SIZE) {
5446 		server->large_buf = true;
5447 		memcpy(server->bigbuf, buf, server->total_read);
5448 		buf = server->bigbuf;
5449 	}
5450 
5451 	/* now read the rest */
5452 	length = cifs_read_from_socket(server, buf + HEADER_SIZE(server) - 1,
5453 				pdu_length - HEADER_SIZE(server) + 1);
5454 	if (length < 0)
5455 		return length;
5456 	server->total_read += length;
5457 
5458 	buf_size = pdu_length - sizeof(struct smb2_transform_hdr);
5459 	length = decrypt_raw_data(server, buf, buf_size, NULL, false);
5460 	if (length)
5461 		return length;
5462 	pdu_length = buf_size;
5463 
5464 	next_is_large = server->large_buf;
5465 one_more:
5466 	shdr = (struct smb2_hdr *)buf;
5467 	next_cmd = le32_to_cpu(shdr->NextCommand);
5468 	server->total_read = next_cmd ? next_cmd : pdu_length;
5469 
5470 	if (*num_mids >= MAX_COMPOUND) {
5471 		cifs_server_dbg(VFS, "too many PDUs in compound\n");
5472 		return -1;
5473 	}
5474 
5475 	if (next_cmd) {
5476 		if (next_cmd < MID_HEADER_SIZE(server) ||
5477 		    next_cmd > pdu_length ||
5478 		    pdu_length - next_cmd < MID_HEADER_SIZE(server)) {
5479 			unsigned int max_next = pdu_length > (unsigned int)MID_HEADER_SIZE(server) ?
5480 					pdu_length - (unsigned int)MID_HEADER_SIZE(server) : 0;
5481 			cifs_server_dbg(VFS, "invalid NextCommand offset %u out of range [%zu, %u]\n",
5482 					next_cmd, MID_HEADER_SIZE(server), max_next);
5483 			return -1;
5484 		}
5485 		if (next_is_large)
5486 			next_buffer = (char *)cifs_buf_get();
5487 		else
5488 			next_buffer = (char *)cifs_small_buf_get();
5489 		if (!next_buffer) {
5490 			cifs_server_dbg(VFS, "No memory for (large) SMB response\n");
5491 			return -1;
5492 		}
5493 		memcpy(next_buffer, buf + next_cmd, pdu_length - next_cmd);
5494 	}
5495 
5496 	mid_entry = smb2_find_mid(server, buf);
5497 	if (mid_entry == NULL)
5498 		cifs_dbg(FYI, "mid not found\n");
5499 	else {
5500 		cifs_dbg(FYI, "mid found\n");
5501 		mid_entry->decrypted = true;
5502 		mid_entry->resp_buf_size = server->pdu_size;
5503 	}
5504 
5505 	bufs[*num_mids] = buf;
5506 	mids[(*num_mids)++] = mid_entry;
5507 
5508 	if (mid_entry && mid_entry->handle)
5509 		ret = mid_entry->handle(server, mid_entry);
5510 	else
5511 		ret = cifs_handle_standard(server, mid_entry);
5512 
5513 	if (ret == 0 && next_cmd) {
5514 		pdu_length -= next_cmd;
5515 		server->large_buf = next_is_large;
5516 		if (next_is_large)
5517 			server->bigbuf = buf = next_buffer;
5518 		else
5519 			server->smallbuf = buf = next_buffer;
5520 		next_buffer = NULL;
5521 		goto one_more;
5522 	} else if (ret != 0) {
5523 		/*
5524 		 * ret != 0 here means that we didn't get to handle_mid() thus
5525 		 * server->smallbuf and server->bigbuf are still valid. We need
5526 		 * to free next_buffer because it is not going to be used
5527 		 * anywhere.
5528 		 */
5529 		if (next_is_large)
5530 			free_rsp_buf(CIFS_LARGE_BUFFER, next_buffer);
5531 		else
5532 			free_rsp_buf(CIFS_SMALL_BUFFER, next_buffer);
5533 	}
5534 
5535 	return ret;
5536 }
5537 
5538 static int
5539 smb3_receive_transform(struct TCP_Server_Info *server,
5540 		       struct mid_q_entry **mids, char **bufs, int *num_mids)
5541 {
5542 	char *buf = server->smallbuf;
5543 	unsigned int pdu_length = server->pdu_size;
5544 	struct smb2_transform_hdr *tr_hdr = (struct smb2_transform_hdr *)buf;
5545 	unsigned int orig_len = le32_to_cpu(tr_hdr->OriginalMessageSize);
5546 
5547 	if (pdu_length < sizeof(struct smb2_transform_hdr) +
5548 						sizeof(struct smb2_hdr)) {
5549 		cifs_server_dbg(VFS, "Transform message is too small (%u)\n",
5550 			 pdu_length);
5551 		cifs_reconnect(server, true);
5552 		return -ECONNABORTED;
5553 	}
5554 
5555 	if (pdu_length < orig_len + sizeof(struct smb2_transform_hdr)) {
5556 		cifs_server_dbg(VFS, "Transform message is broken\n");
5557 		cifs_reconnect(server, true);
5558 		return -ECONNABORTED;
5559 	}
5560 
5561 	/* TODO: add support for compounds containing READ. */
5562 	if (pdu_length > CIFSMaxBufSize + MAX_HEADER_SIZE(server)) {
5563 		return receive_encrypted_read(server, &mids[0], num_mids);
5564 	}
5565 
5566 	return receive_encrypted_standard(server, mids, bufs, num_mids);
5567 }
5568 
5569 int
5570 smb3_handle_read_data(struct TCP_Server_Info *server, struct mid_q_entry *mid)
5571 {
5572 	char *buf = server->large_buf ? server->bigbuf : server->smallbuf;
5573 
5574 	return handle_read_data(server, mid, buf, server->pdu_size,
5575 				NULL, 0, false);
5576 }
5577 
5578 static int smb2_next_header(struct TCP_Server_Info *server, char *buf,
5579 			    unsigned int *noff)
5580 {
5581 	struct smb2_hdr *hdr = (struct smb2_hdr *)buf;
5582 	struct smb2_transform_hdr *t_hdr = (struct smb2_transform_hdr *)buf;
5583 
5584 	if (hdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM) {
5585 		*noff = le32_to_cpu(t_hdr->OriginalMessageSize);
5586 		if (unlikely(check_add_overflow(*noff, sizeof(*t_hdr), noff)))
5587 			return -EINVAL;
5588 	} else {
5589 		*noff = le32_to_cpu(hdr->NextCommand);
5590 	}
5591 	if (unlikely(*noff && *noff < MID_HEADER_SIZE(server)))
5592 		return -EINVAL;
5593 	return 0;
5594 }
5595 
5596 int __cifs_sfu_make_node(unsigned int xid, struct inode *inode,
5597 				struct dentry *dentry, struct cifs_tcon *tcon,
5598 				const char *full_path, umode_t mode, dev_t dev,
5599 				const char *symname)
5600 {
5601 	struct TCP_Server_Info *server = tcon->ses->server;
5602 	struct cifs_open_parms oparms;
5603 	struct cifs_open_info_data idata = {};
5604 	struct cifs_io_parms io_parms = {};
5605 	struct cifs_sb_info *cifs_sb = CIFS_SB(inode->i_sb);
5606 	struct cifs_fid fid;
5607 	unsigned int bytes_written;
5608 	u8 type[8];
5609 	int type_len = 0;
5610 	struct {
5611 		__le64 major;
5612 		__le64 minor;
5613 	} __packed pdev = {};
5614 	__le16 *symname_utf16 = NULL;
5615 	u8 *data = NULL;
5616 	int data_len = 0;
5617 	struct kvec iov[3];
5618 	__u32 oplock = server->oplocks ? REQ_OPLOCK : 0;
5619 	int rc;
5620 
5621 	switch (mode & S_IFMT) {
5622 	case S_IFCHR:
5623 		type_len = 8;
5624 		memcpy(type, "IntxCHR\0", type_len);
5625 		pdev.major = cpu_to_le64(MAJOR(dev));
5626 		pdev.minor = cpu_to_le64(MINOR(dev));
5627 		data = (u8 *)&pdev;
5628 		data_len = sizeof(pdev);
5629 		break;
5630 	case S_IFBLK:
5631 		type_len = 8;
5632 		memcpy(type, "IntxBLK\0", type_len);
5633 		pdev.major = cpu_to_le64(MAJOR(dev));
5634 		pdev.minor = cpu_to_le64(MINOR(dev));
5635 		data = (u8 *)&pdev;
5636 		data_len = sizeof(pdev);
5637 		break;
5638 	case S_IFLNK:
5639 		type_len = 8;
5640 		memcpy(type, "IntxLNK\1", type_len);
5641 		symname_utf16 = cifs_strndup_to_utf16(symname, strlen(symname),
5642 						      &data_len, cifs_sb->local_nls,
5643 						      NO_MAP_UNI_RSVD);
5644 		if (!symname_utf16) {
5645 			rc = -ENOMEM;
5646 			goto out;
5647 		}
5648 		data_len -= 2; /* symlink is without trailing wide-nul */
5649 		data = (u8 *)symname_utf16;
5650 		break;
5651 	case S_IFSOCK:
5652 		/* SFU socket is system file with one zero byte */
5653 		type_len = 1;
5654 		type[0] = '\0';
5655 		break;
5656 	case S_IFIFO:
5657 		/* SFU fifo is system file which is empty */
5658 		type_len = 0;
5659 		break;
5660 	default:
5661 		rc = -EPERM;
5662 		goto out;
5663 	}
5664 
5665 	oparms = CIFS_OPARMS(cifs_sb, tcon, full_path, GENERIC_WRITE,
5666 			     FILE_CREATE, CREATE_NOT_DIR |
5667 			     CREATE_OPTION_SPECIAL, ACL_NO_MODE);
5668 	oparms.fid = &fid;
5669 	idata.contains_posix_file_info = false;
5670 	rc = server->ops->open(xid, &oparms, &oplock, &idata);
5671 	if (rc)
5672 		goto out;
5673 
5674 	/*
5675 	 * Check if the server honored ATTR_SYSTEM flag by CREATE_OPTION_SPECIAL
5676 	 * option. If not then server does not support ATTR_SYSTEM and newly
5677 	 * created file is not SFU compatible, which means that the call failed.
5678 	 */
5679 	if (!(le32_to_cpu(idata.fi.Attributes) & ATTR_SYSTEM)) {
5680 		rc = -EOPNOTSUPP;
5681 		goto out_close;
5682 	}
5683 
5684 	if (type_len + data_len > 0) {
5685 		io_parms.pid = current->tgid;
5686 		io_parms.tcon = tcon;
5687 		io_parms.length = type_len + data_len;
5688 		iov[1].iov_base = type;
5689 		iov[1].iov_len = type_len;
5690 		iov[2].iov_base = data;
5691 		iov[2].iov_len = data_len;
5692 
5693 		rc = server->ops->sync_write(xid, &fid, &io_parms,
5694 					     &bytes_written,
5695 					     iov, ARRAY_SIZE(iov)-1);
5696 	}
5697 
5698 out_close:
5699 	server->ops->close(xid, tcon, &fid);
5700 
5701 	/*
5702 	 * If CREATE was successful but either setting ATTR_SYSTEM failed or
5703 	 * writing type/data information failed then remove the intermediate
5704 	 * object created by CREATE. Otherwise intermediate empty object stay
5705 	 * on the server.
5706 	 */
5707 	if (rc)
5708 		server->ops->unlink(xid, tcon, full_path, cifs_sb, NULL);
5709 
5710 out:
5711 	kfree(symname_utf16);
5712 	return rc;
5713 }
5714 
5715 int cifs_sfu_make_node(unsigned int xid, struct inode *inode,
5716 		       struct dentry *dentry, struct cifs_tcon *tcon,
5717 		       const char *full_path, umode_t mode, dev_t dev)
5718 {
5719 	struct inode *new = NULL;
5720 	int rc;
5721 
5722 	rc = __cifs_sfu_make_node(xid, inode, dentry, tcon,
5723 				  full_path, mode, dev, NULL);
5724 	if (rc)
5725 		return rc;
5726 
5727 	if (tcon->posix_extensions) {
5728 		rc = smb311_posix_get_inode_info(&new, full_path, NULL,
5729 						 inode->i_sb, xid);
5730 	} else if (tcon->unix_ext) {
5731 		rc = cifs_get_inode_info_unix(&new, full_path,
5732 					      inode->i_sb, xid);
5733 	} else {
5734 		rc = cifs_get_inode_info(&new, full_path, NULL,
5735 					 inode->i_sb, xid, NULL);
5736 	}
5737 	if (!rc)
5738 		d_instantiate(dentry, new);
5739 	return rc;
5740 }
5741 
5742 static int smb2_make_node(unsigned int xid, struct inode *inode,
5743 			  struct dentry *dentry, struct cifs_tcon *tcon,
5744 			  const char *full_path, umode_t mode, dev_t dev)
5745 {
5746 	unsigned int sbflags = cifs_sb_flags(CIFS_SB(inode));
5747 	int rc = -EOPNOTSUPP;
5748 
5749 	/*
5750 	 * Check if mounted with mount parm 'sfu' mount parm.
5751 	 * SFU emulation should work with all servers, but only
5752 	 * supports block and char device, socket & fifo,
5753 	 * and was used by default in earlier versions of Windows
5754 	 */
5755 	if (sbflags & CIFS_MOUNT_UNX_EMUL) {
5756 		rc = cifs_sfu_make_node(xid, inode, dentry, tcon,
5757 					full_path, mode, dev);
5758 	} else if (CIFS_REPARSE_SUPPORT(tcon)) {
5759 		rc = mknod_reparse(xid, inode, dentry, tcon,
5760 				   full_path, mode, dev);
5761 	}
5762 	return rc;
5763 }
5764 
5765 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
5766 struct smb_version_operations smb20_operations = {
5767 	.compare_fids = smb2_compare_fids,
5768 	.setup_request = smb2_setup_request,
5769 	.setup_async_request = smb2_setup_async_request,
5770 	.check_receive = smb2_check_receive,
5771 	.add_credits = smb2_add_credits,
5772 	.set_credits = smb2_set_credits,
5773 	.get_credits_field = smb2_get_credits_field,
5774 	.get_credits = smb2_get_credits,
5775 	.wait_mtu_credits = cifs_wait_mtu_credits,
5776 	.get_next_mid = smb2_get_next_mid,
5777 	.revert_current_mid = smb2_revert_current_mid,
5778 	.read_data_offset = smb2_read_data_offset,
5779 	.read_data_length = smb2_read_data_length,
5780 	.map_error = map_smb2_to_linux_error,
5781 	.find_mid = smb2_find_mid,
5782 	.check_message = smb2_check_message,
5783 	.dump_detail = smb2_dump_detail,
5784 	.clear_stats = smb2_clear_stats,
5785 	.print_stats = smb2_print_stats,
5786 	.is_oplock_break = smb2_is_valid_oplock_break,
5787 	.handle_cancelled_mid = smb2_handle_cancelled_mid,
5788 	.downgrade_oplock = smb2_downgrade_oplock,
5789 	.need_neg = smb2_need_neg,
5790 	.negotiate = smb2_negotiate,
5791 	.negotiate_wsize = smb2_negotiate_wsize,
5792 	.negotiate_rsize = smb2_negotiate_rsize,
5793 	.sess_setup = SMB2_sess_setup,
5794 	.logoff = SMB2_logoff,
5795 	.tree_connect = SMB2_tcon,
5796 	.tree_disconnect = SMB2_tdis,
5797 	.qfs_tcon = smb2_qfs_tcon,
5798 	.is_path_accessible = smb2_is_path_accessible,
5799 	.can_echo = smb2_can_echo,
5800 	.echo = SMB2_echo,
5801 	.query_path_info = smb2_query_path_info,
5802 	.query_reparse_point = smb2_query_reparse_point,
5803 	.get_srv_inum = smb2_get_srv_inum,
5804 	.query_file_info = smb2_query_file_info,
5805 	.set_path_size = smb2_set_path_size,
5806 	.set_file_size = smb2_set_file_size,
5807 	.set_file_info = smb2_set_file_info,
5808 	.set_compression = smb2_set_compression,
5809 	.mkdir = smb2_mkdir,
5810 	.mkdir_setinfo = smb2_mkdir_setinfo,
5811 	.rmdir = smb2_rmdir,
5812 	.unlink = smb2_unlink,
5813 	.rename = smb2_rename_path,
5814 	.create_hardlink = smb2_create_hardlink,
5815 	.get_reparse_point_buffer = smb2_get_reparse_point_buffer,
5816 	.query_mf_symlink = smb2_query_mf_symlink,
5817 	.create_mf_symlink = smb2_create_mf_symlink,
5818 	.create_reparse_inode = smb2_create_reparse_inode,
5819 	.open = smb2_open_file,
5820 	.set_fid = smb2_set_fid,
5821 	.close = smb2_close_file,
5822 	.flush = smb2_flush_file,
5823 	.async_readv = smb2_async_readv,
5824 	.async_writev = smb2_async_writev,
5825 	.sync_read = smb2_sync_read,
5826 	.sync_write = smb2_sync_write,
5827 	.query_dir_first = smb2_query_dir_first,
5828 	.query_dir_next = smb2_query_dir_next,
5829 	.close_dir = smb2_close_dir,
5830 	.calc_smb_size = smb2_calc_size,
5831 	.is_status_pending = smb2_is_status_pending,
5832 	.is_session_expired = smb2_is_session_expired,
5833 	.oplock_response = smb2_oplock_response,
5834 	.queryfs = smb2_queryfs,
5835 	.mand_lock = smb2_mand_lock,
5836 	.mand_unlock_range = smb2_unlock_range,
5837 	.push_mand_locks = smb2_push_mandatory_locks,
5838 	.get_lease_key = smb2_get_lease_key,
5839 	.set_lease_key = smb2_set_lease_key,
5840 	.new_lease_key = smb2_new_lease_key,
5841 	.is_read_op = smb2_is_read_op,
5842 	.set_oplock_level = smb2_set_oplock_level,
5843 	.create_lease_buf = smb2_create_lease_buf,
5844 	.parse_lease_buf = smb2_parse_lease_buf,
5845 	.copychunk_range = smb2_copychunk_range,
5846 	.wp_retry_size = smb2_wp_retry_size,
5847 	.dir_needs_close = smb2_dir_needs_close,
5848 	.get_dfs_refer = smb2_get_dfs_refer,
5849 	.select_sectype = smb2_select_sectype,
5850 #ifdef CONFIG_CIFS_XATTR
5851 	.query_all_EAs = smb2_query_eas,
5852 	.set_EA = smb2_set_ea,
5853 #endif /* CIFS_XATTR */
5854 	.get_acl = get_smb2_acl,
5855 	.get_acl_by_fid = get_smb2_acl_by_fid,
5856 	.set_acl = set_smb2_acl,
5857 	.next_header = smb2_next_header,
5858 	.ioctl_query_info = smb2_ioctl_query_info,
5859 	.make_node = smb2_make_node,
5860 	.fiemap = smb3_fiemap,
5861 	.llseek = smb3_llseek,
5862 	.is_status_io_timeout = smb2_is_status_io_timeout,
5863 	.is_network_name_deleted = smb2_is_network_name_deleted,
5864 	.rename_pending_delete = smb2_rename_pending_delete,
5865 };
5866 #endif /* CIFS_ALLOW_INSECURE_LEGACY */
5867 
5868 struct smb_version_operations smb21_operations = {
5869 	.compare_fids = smb2_compare_fids,
5870 	.setup_request = smb2_setup_request,
5871 	.setup_async_request = smb2_setup_async_request,
5872 	.check_receive = smb2_check_receive,
5873 	.add_credits = smb2_add_credits,
5874 	.set_credits = smb2_set_credits,
5875 	.get_credits_field = smb2_get_credits_field,
5876 	.get_credits = smb2_get_credits,
5877 	.wait_mtu_credits = smb2_wait_mtu_credits,
5878 	.adjust_credits = smb2_adjust_credits,
5879 	.get_next_mid = smb2_get_next_mid,
5880 	.revert_current_mid = smb2_revert_current_mid,
5881 	.read_data_offset = smb2_read_data_offset,
5882 	.read_data_length = smb2_read_data_length,
5883 	.map_error = map_smb2_to_linux_error,
5884 	.find_mid = smb2_find_mid,
5885 	.check_message = smb2_check_message,
5886 	.dump_detail = smb2_dump_detail,
5887 	.clear_stats = smb2_clear_stats,
5888 	.print_stats = smb2_print_stats,
5889 	.is_oplock_break = smb2_is_valid_oplock_break,
5890 	.handle_cancelled_mid = smb2_handle_cancelled_mid,
5891 	.downgrade_oplock = smb2_downgrade_oplock,
5892 	.need_neg = smb2_need_neg,
5893 	.negotiate = smb2_negotiate,
5894 	.negotiate_wsize = smb2_negotiate_wsize,
5895 	.negotiate_rsize = smb2_negotiate_rsize,
5896 	.sess_setup = SMB2_sess_setup,
5897 	.logoff = SMB2_logoff,
5898 	.tree_connect = SMB2_tcon,
5899 	.tree_disconnect = SMB2_tdis,
5900 	.qfs_tcon = smb2_qfs_tcon,
5901 	.is_path_accessible = smb2_is_path_accessible,
5902 	.can_echo = smb2_can_echo,
5903 	.echo = SMB2_echo,
5904 	.query_path_info = smb2_query_path_info,
5905 	.query_reparse_point = smb2_query_reparse_point,
5906 	.get_srv_inum = smb2_get_srv_inum,
5907 	.query_file_info = smb2_query_file_info,
5908 	.set_path_size = smb2_set_path_size,
5909 	.set_file_size = smb2_set_file_size,
5910 	.set_file_info = smb2_set_file_info,
5911 	.set_compression = smb2_set_compression,
5912 	.mkdir = smb2_mkdir,
5913 	.mkdir_setinfo = smb2_mkdir_setinfo,
5914 	.rmdir = smb2_rmdir,
5915 	.unlink = smb2_unlink,
5916 	.rename = smb2_rename_path,
5917 	.create_hardlink = smb2_create_hardlink,
5918 	.get_reparse_point_buffer = smb2_get_reparse_point_buffer,
5919 	.query_mf_symlink = smb2_query_mf_symlink,
5920 	.create_mf_symlink = smb2_create_mf_symlink,
5921 	.create_reparse_inode = smb2_create_reparse_inode,
5922 	.open = smb2_open_file,
5923 	.set_fid = smb2_set_fid,
5924 	.close = smb2_close_file,
5925 	.flush = smb2_flush_file,
5926 	.async_readv = smb2_async_readv,
5927 	.async_writev = smb2_async_writev,
5928 	.sync_read = smb2_sync_read,
5929 	.sync_write = smb2_sync_write,
5930 	.query_dir_first = smb2_query_dir_first,
5931 	.query_dir_next = smb2_query_dir_next,
5932 	.close_dir = smb2_close_dir,
5933 	.calc_smb_size = smb2_calc_size,
5934 	.is_status_pending = smb2_is_status_pending,
5935 	.is_session_expired = smb2_is_session_expired,
5936 	.oplock_response = smb2_oplock_response,
5937 	.queryfs = smb2_queryfs,
5938 	.mand_lock = smb2_mand_lock,
5939 	.mand_unlock_range = smb2_unlock_range,
5940 	.push_mand_locks = smb2_push_mandatory_locks,
5941 	.get_lease_key = smb2_get_lease_key,
5942 	.set_lease_key = smb2_set_lease_key,
5943 	.new_lease_key = smb2_new_lease_key,
5944 	.is_read_op = smb21_is_read_op,
5945 	.set_oplock_level = smb21_set_oplock_level,
5946 	.create_lease_buf = smb2_create_lease_buf,
5947 	.parse_lease_buf = smb2_parse_lease_buf,
5948 	.copychunk_range = smb2_copychunk_range,
5949 	.wp_retry_size = smb2_wp_retry_size,
5950 	.dir_needs_close = smb2_dir_needs_close,
5951 	.enum_snapshots = smb3_enum_snapshots,
5952 	.notify = smb3_notify,
5953 	.get_dfs_refer = smb2_get_dfs_refer,
5954 	.select_sectype = smb2_select_sectype,
5955 #ifdef CONFIG_CIFS_XATTR
5956 	.query_all_EAs = smb2_query_eas,
5957 	.set_EA = smb2_set_ea,
5958 #endif /* CIFS_XATTR */
5959 	.get_acl = get_smb2_acl,
5960 	.get_acl_by_fid = get_smb2_acl_by_fid,
5961 	.set_acl = set_smb2_acl,
5962 	.next_header = smb2_next_header,
5963 	.ioctl_query_info = smb2_ioctl_query_info,
5964 	.make_node = smb2_make_node,
5965 	.fiemap = smb3_fiemap,
5966 	.llseek = smb3_llseek,
5967 	.is_status_io_timeout = smb2_is_status_io_timeout,
5968 	.is_network_name_deleted = smb2_is_network_name_deleted,
5969 	.rename_pending_delete = smb2_rename_pending_delete,
5970 };
5971 
5972 struct smb_version_operations smb30_operations = {
5973 	.compare_fids = smb2_compare_fids,
5974 	.setup_request = smb2_setup_request,
5975 	.setup_async_request = smb2_setup_async_request,
5976 	.check_receive = smb2_check_receive,
5977 	.add_credits = smb2_add_credits,
5978 	.set_credits = smb2_set_credits,
5979 	.get_credits_field = smb2_get_credits_field,
5980 	.get_credits = smb2_get_credits,
5981 	.wait_mtu_credits = smb2_wait_mtu_credits,
5982 	.adjust_credits = smb2_adjust_credits,
5983 	.get_next_mid = smb2_get_next_mid,
5984 	.revert_current_mid = smb2_revert_current_mid,
5985 	.read_data_offset = smb2_read_data_offset,
5986 	.read_data_length = smb2_read_data_length,
5987 	.map_error = map_smb2_to_linux_error,
5988 	.find_mid = smb2_find_mid,
5989 	.check_message = smb2_check_message,
5990 	.dump_detail = smb2_dump_detail,
5991 	.clear_stats = smb2_clear_stats,
5992 	.print_stats = smb2_print_stats,
5993 	.dump_share_caps = smb2_dump_share_caps,
5994 	.is_oplock_break = smb2_is_valid_oplock_break,
5995 	.handle_cancelled_mid = smb2_handle_cancelled_mid,
5996 	.downgrade_oplock = smb3_downgrade_oplock,
5997 	.need_neg = smb2_need_neg,
5998 	.negotiate = smb2_negotiate,
5999 	.negotiate_wsize = smb3_negotiate_wsize,
6000 	.negotiate_rsize = smb3_negotiate_rsize,
6001 	.sess_setup = SMB2_sess_setup,
6002 	.logoff = SMB2_logoff,
6003 	.tree_connect = SMB2_tcon,
6004 	.tree_disconnect = SMB2_tdis,
6005 	.qfs_tcon = smb3_qfs_tcon,
6006 	.query_server_interfaces = SMB3_request_interfaces,
6007 	.is_path_accessible = smb2_is_path_accessible,
6008 	.can_echo = smb2_can_echo,
6009 	.echo = SMB2_echo,
6010 	.query_path_info = smb2_query_path_info,
6011 	/* WSL tags introduced long after smb2.1, enable for SMB3, 3.11 only */
6012 	.query_reparse_point = smb2_query_reparse_point,
6013 	.get_srv_inum = smb2_get_srv_inum,
6014 	.query_file_info = smb2_query_file_info,
6015 	.set_path_size = smb2_set_path_size,
6016 	.set_file_size = smb2_set_file_size,
6017 	.set_file_info = smb2_set_file_info,
6018 	.set_compression = smb2_set_compression,
6019 	.mkdir = smb2_mkdir,
6020 	.mkdir_setinfo = smb2_mkdir_setinfo,
6021 	.rmdir = smb2_rmdir,
6022 	.unlink = smb2_unlink,
6023 	.rename = smb2_rename_path,
6024 	.create_hardlink = smb2_create_hardlink,
6025 	.get_reparse_point_buffer = smb2_get_reparse_point_buffer,
6026 	.query_mf_symlink = smb2_query_mf_symlink,
6027 	.create_mf_symlink = smb2_create_mf_symlink,
6028 	.create_reparse_inode = smb2_create_reparse_inode,
6029 	.open = smb2_open_file,
6030 	.set_fid = smb2_set_fid,
6031 	.close = smb2_close_file,
6032 	.close_getattr = smb2_close_getattr,
6033 	.flush = smb2_flush_file,
6034 	.async_readv = smb2_async_readv,
6035 	.async_writev = smb2_async_writev,
6036 	.sync_read = smb2_sync_read,
6037 	.sync_write = smb2_sync_write,
6038 	.query_dir_first = smb2_query_dir_first,
6039 	.query_dir_next = smb2_query_dir_next,
6040 	.close_dir = smb2_close_dir,
6041 	.calc_smb_size = smb2_calc_size,
6042 	.is_status_pending = smb2_is_status_pending,
6043 	.is_session_expired = smb2_is_session_expired,
6044 	.oplock_response = smb2_oplock_response,
6045 	.queryfs = smb2_queryfs,
6046 	.mand_lock = smb2_mand_lock,
6047 	.mand_unlock_range = smb2_unlock_range,
6048 	.push_mand_locks = smb2_push_mandatory_locks,
6049 	.get_lease_key = smb2_get_lease_key,
6050 	.set_lease_key = smb2_set_lease_key,
6051 	.new_lease_key = smb2_new_lease_key,
6052 	.generate_signingkey = generate_smb30signingkey,
6053 	.set_integrity  = smb3_set_integrity,
6054 	.is_read_op = smb21_is_read_op,
6055 	.set_oplock_level = smb3_set_oplock_level,
6056 	.create_lease_buf = smb3_create_lease_buf,
6057 	.parse_lease_buf = smb3_parse_lease_buf,
6058 	.copychunk_range = smb2_copychunk_range,
6059 	.duplicate_extents = smb2_duplicate_extents,
6060 	.validate_negotiate = smb3_validate_negotiate,
6061 	.wp_retry_size = smb2_wp_retry_size,
6062 	.dir_needs_close = smb2_dir_needs_close,
6063 	.fallocate = smb3_fallocate,
6064 	.enum_snapshots = smb3_enum_snapshots,
6065 	.notify = smb3_notify,
6066 	.init_transform_rq = smb3_init_transform_rq,
6067 	.is_transform_hdr = smb3_is_transform_hdr,
6068 	.receive_transform = smb3_receive_transform,
6069 	.get_dfs_refer = smb2_get_dfs_refer,
6070 	.select_sectype = smb2_select_sectype,
6071 #ifdef CONFIG_CIFS_XATTR
6072 	.query_all_EAs = smb2_query_eas,
6073 	.set_EA = smb2_set_ea,
6074 #endif /* CIFS_XATTR */
6075 	.get_acl = get_smb2_acl,
6076 	.get_acl_by_fid = get_smb2_acl_by_fid,
6077 	.set_acl = set_smb2_acl,
6078 	.next_header = smb2_next_header,
6079 	.ioctl_query_info = smb2_ioctl_query_info,
6080 	.make_node = smb2_make_node,
6081 	.fiemap = smb3_fiemap,
6082 	.llseek = smb3_llseek,
6083 	.is_status_io_timeout = smb2_is_status_io_timeout,
6084 	.is_network_name_deleted = smb2_is_network_name_deleted,
6085 	.rename_pending_delete = smb2_rename_pending_delete,
6086 };
6087 
6088 struct smb_version_operations smb311_operations = {
6089 	.compare_fids = smb2_compare_fids,
6090 	.setup_request = smb2_setup_request,
6091 	.setup_async_request = smb2_setup_async_request,
6092 	.check_receive = smb2_check_receive,
6093 	.add_credits = smb2_add_credits,
6094 	.set_credits = smb2_set_credits,
6095 	.get_credits_field = smb2_get_credits_field,
6096 	.get_credits = smb2_get_credits,
6097 	.wait_mtu_credits = smb2_wait_mtu_credits,
6098 	.adjust_credits = smb2_adjust_credits,
6099 	.get_next_mid = smb2_get_next_mid,
6100 	.revert_current_mid = smb2_revert_current_mid,
6101 	.read_data_offset = smb2_read_data_offset,
6102 	.read_data_length = smb2_read_data_length,
6103 	.map_error = map_smb2_to_linux_error,
6104 	.find_mid = smb2_find_mid,
6105 	.check_message = smb2_check_message,
6106 	.dump_detail = smb2_dump_detail,
6107 	.clear_stats = smb2_clear_stats,
6108 	.print_stats = smb2_print_stats,
6109 	.dump_share_caps = smb2_dump_share_caps,
6110 	.is_oplock_break = smb2_is_valid_oplock_break,
6111 	.handle_cancelled_mid = smb2_handle_cancelled_mid,
6112 	.downgrade_oplock = smb3_downgrade_oplock,
6113 	.need_neg = smb2_need_neg,
6114 	.negotiate = smb2_negotiate,
6115 	.negotiate_wsize = smb3_negotiate_wsize,
6116 	.negotiate_rsize = smb3_negotiate_rsize,
6117 	.sess_setup = SMB2_sess_setup,
6118 	.logoff = SMB2_logoff,
6119 	.tree_connect = SMB2_tcon,
6120 	.tree_disconnect = SMB2_tdis,
6121 	.qfs_tcon = smb3_qfs_tcon,
6122 	.query_server_interfaces = SMB3_request_interfaces,
6123 	.is_path_accessible = smb2_is_path_accessible,
6124 	.can_echo = smb2_can_echo,
6125 	.echo = SMB2_echo,
6126 	.query_path_info = smb2_query_path_info,
6127 	.query_reparse_point = smb2_query_reparse_point,
6128 	.get_srv_inum = smb2_get_srv_inum,
6129 	.query_file_info = smb2_query_file_info,
6130 	.set_path_size = smb2_set_path_size,
6131 	.set_file_size = smb2_set_file_size,
6132 	.set_file_info = smb2_set_file_info,
6133 	.set_compression = smb2_set_compression,
6134 	.mkdir = smb2_mkdir,
6135 	.mkdir_setinfo = smb2_mkdir_setinfo,
6136 	.posix_mkdir = smb311_posix_mkdir,
6137 	.rmdir = smb2_rmdir,
6138 	.unlink = smb2_unlink,
6139 	.rename = smb2_rename_path,
6140 	.create_hardlink = smb2_create_hardlink,
6141 	.get_reparse_point_buffer = smb2_get_reparse_point_buffer,
6142 	.query_mf_symlink = smb2_query_mf_symlink,
6143 	.create_mf_symlink = smb2_create_mf_symlink,
6144 	.create_reparse_inode = smb2_create_reparse_inode,
6145 	.open = smb2_open_file,
6146 	.set_fid = smb2_set_fid,
6147 	.close = smb2_close_file,
6148 	.close_getattr = smb2_close_getattr,
6149 	.flush = smb2_flush_file,
6150 	.async_readv = smb2_async_readv,
6151 	.async_writev = smb2_async_writev,
6152 	.sync_read = smb2_sync_read,
6153 	.sync_write = smb2_sync_write,
6154 	.query_dir_first = smb2_query_dir_first,
6155 	.query_dir_next = smb2_query_dir_next,
6156 	.close_dir = smb2_close_dir,
6157 	.calc_smb_size = smb2_calc_size,
6158 	.is_status_pending = smb2_is_status_pending,
6159 	.is_session_expired = smb2_is_session_expired,
6160 	.oplock_response = smb2_oplock_response,
6161 	.queryfs = smb311_queryfs,
6162 	.mand_lock = smb2_mand_lock,
6163 	.mand_unlock_range = smb2_unlock_range,
6164 	.push_mand_locks = smb2_push_mandatory_locks,
6165 	.get_lease_key = smb2_get_lease_key,
6166 	.set_lease_key = smb2_set_lease_key,
6167 	.new_lease_key = smb2_new_lease_key,
6168 	.generate_signingkey = generate_smb311signingkey,
6169 	.set_integrity  = smb3_set_integrity,
6170 	.is_read_op = smb21_is_read_op,
6171 	.set_oplock_level = smb3_set_oplock_level,
6172 	.create_lease_buf = smb3_create_lease_buf,
6173 	.parse_lease_buf = smb3_parse_lease_buf,
6174 	.copychunk_range = smb2_copychunk_range,
6175 	.duplicate_extents = smb2_duplicate_extents,
6176 /*	.validate_negotiate = smb3_validate_negotiate, */ /* not used in 3.11 */
6177 	.wp_retry_size = smb2_wp_retry_size,
6178 	.dir_needs_close = smb2_dir_needs_close,
6179 	.fallocate = smb3_fallocate,
6180 	.enum_snapshots = smb3_enum_snapshots,
6181 	.notify = smb3_notify,
6182 	.init_transform_rq = smb3_init_transform_rq,
6183 	.is_transform_hdr = smb3_is_transform_hdr,
6184 	.receive_transform = smb3_receive_transform,
6185 	.get_dfs_refer = smb2_get_dfs_refer,
6186 	.select_sectype = smb2_select_sectype,
6187 #ifdef CONFIG_CIFS_XATTR
6188 	.query_all_EAs = smb2_query_eas,
6189 	.set_EA = smb2_set_ea,
6190 #endif /* CIFS_XATTR */
6191 	.get_acl = get_smb2_acl,
6192 	.get_acl_by_fid = get_smb2_acl_by_fid,
6193 	.set_acl = set_smb2_acl,
6194 	.next_header = smb2_next_header,
6195 	.ioctl_query_info = smb2_ioctl_query_info,
6196 	.make_node = smb2_make_node,
6197 	.fiemap = smb3_fiemap,
6198 	.llseek = smb3_llseek,
6199 	.is_status_io_timeout = smb2_is_status_io_timeout,
6200 	.is_network_name_deleted = smb2_is_network_name_deleted,
6201 	.rename_pending_delete = smb2_rename_pending_delete,
6202 };
6203 
6204 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
6205 struct smb_version_values smb20_values = {
6206 	.version_string = SMB20_VERSION_STRING,
6207 	.protocol_id = SMB20_PROT_ID,
6208 	.req_capabilities = 0, /* MBZ */
6209 	.large_lock_type = 0,
6210 	.exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE,
6211 	.shared_lock_type = SMB2_LOCKFLAG_SHARED,
6212 	.unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
6213 	.header_size = sizeof(struct smb2_hdr),
6214 	.max_header_size = MAX_SMB2_HDR_SIZE,
6215 	.read_rsp_size = sizeof(struct smb2_read_rsp),
6216 	.lock_cmd = SMB2_LOCK,
6217 	.cap_unix = 0,
6218 	.cap_nt_find = SMB2_NT_FIND,
6219 	.cap_large_files = SMB2_LARGE_FILES,
6220 	.signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
6221 	.signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
6222 	.create_lease_size = sizeof(struct create_lease),
6223 };
6224 #endif /* ALLOW_INSECURE_LEGACY */
6225 
6226 struct smb_version_values smb21_values = {
6227 	.version_string = SMB21_VERSION_STRING,
6228 	.protocol_id = SMB21_PROT_ID,
6229 	.req_capabilities = 0, /* MBZ on negotiate req until SMB3 dialect */
6230 	.large_lock_type = 0,
6231 	.exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE,
6232 	.shared_lock_type = SMB2_LOCKFLAG_SHARED,
6233 	.unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
6234 	.header_size = sizeof(struct smb2_hdr),
6235 	.max_header_size = MAX_SMB2_HDR_SIZE,
6236 	.read_rsp_size = sizeof(struct smb2_read_rsp),
6237 	.lock_cmd = SMB2_LOCK,
6238 	.cap_unix = 0,
6239 	.cap_nt_find = SMB2_NT_FIND,
6240 	.cap_large_files = SMB2_LARGE_FILES,
6241 	.signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
6242 	.signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
6243 	.create_lease_size = sizeof(struct create_lease),
6244 };
6245 
6246 struct smb_version_values smb3any_values = {
6247 	.version_string = SMB3ANY_VERSION_STRING,
6248 	.protocol_id = SMB302_PROT_ID, /* doesn't matter, send protocol array */
6249 	.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,
6250 	.large_lock_type = 0,
6251 	.exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE,
6252 	.shared_lock_type = SMB2_LOCKFLAG_SHARED,
6253 	.unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
6254 	.header_size = sizeof(struct smb2_hdr),
6255 	.max_header_size = MAX_SMB2_HDR_SIZE,
6256 	.read_rsp_size = sizeof(struct smb2_read_rsp),
6257 	.lock_cmd = SMB2_LOCK,
6258 	.cap_unix = 0,
6259 	.cap_nt_find = SMB2_NT_FIND,
6260 	.cap_large_files = SMB2_LARGE_FILES,
6261 	.signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
6262 	.signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
6263 	.create_lease_size = sizeof(struct create_lease_v2),
6264 };
6265 
6266 struct smb_version_values smbdefault_values = {
6267 	.version_string = SMBDEFAULT_VERSION_STRING,
6268 	.protocol_id = SMB302_PROT_ID, /* doesn't matter, send protocol array */
6269 	.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,
6270 	.large_lock_type = 0,
6271 	.exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE,
6272 	.shared_lock_type = SMB2_LOCKFLAG_SHARED,
6273 	.unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
6274 	.header_size = sizeof(struct smb2_hdr),
6275 	.max_header_size = MAX_SMB2_HDR_SIZE,
6276 	.read_rsp_size = sizeof(struct smb2_read_rsp),
6277 	.lock_cmd = SMB2_LOCK,
6278 	.cap_unix = 0,
6279 	.cap_nt_find = SMB2_NT_FIND,
6280 	.cap_large_files = SMB2_LARGE_FILES,
6281 	.signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
6282 	.signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
6283 	.create_lease_size = sizeof(struct create_lease_v2),
6284 };
6285 
6286 struct smb_version_values smb30_values = {
6287 	.version_string = SMB30_VERSION_STRING,
6288 	.protocol_id = SMB30_PROT_ID,
6289 	.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,
6290 	.large_lock_type = 0,
6291 	.exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE,
6292 	.shared_lock_type = SMB2_LOCKFLAG_SHARED,
6293 	.unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
6294 	.header_size = sizeof(struct smb2_hdr),
6295 	.max_header_size = MAX_SMB2_HDR_SIZE,
6296 	.read_rsp_size = sizeof(struct smb2_read_rsp),
6297 	.lock_cmd = SMB2_LOCK,
6298 	.cap_unix = 0,
6299 	.cap_nt_find = SMB2_NT_FIND,
6300 	.cap_large_files = SMB2_LARGE_FILES,
6301 	.signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
6302 	.signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
6303 	.create_lease_size = sizeof(struct create_lease_v2),
6304 };
6305 
6306 struct smb_version_values smb302_values = {
6307 	.version_string = SMB302_VERSION_STRING,
6308 	.protocol_id = SMB302_PROT_ID,
6309 	.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,
6310 	.large_lock_type = 0,
6311 	.exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE,
6312 	.shared_lock_type = SMB2_LOCKFLAG_SHARED,
6313 	.unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
6314 	.header_size = sizeof(struct smb2_hdr),
6315 	.max_header_size = MAX_SMB2_HDR_SIZE,
6316 	.read_rsp_size = sizeof(struct smb2_read_rsp),
6317 	.lock_cmd = SMB2_LOCK,
6318 	.cap_unix = 0,
6319 	.cap_nt_find = SMB2_NT_FIND,
6320 	.cap_large_files = SMB2_LARGE_FILES,
6321 	.signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
6322 	.signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
6323 	.create_lease_size = sizeof(struct create_lease_v2),
6324 };
6325 
6326 struct smb_version_values smb311_values = {
6327 	.version_string = SMB311_VERSION_STRING,
6328 	.protocol_id = SMB311_PROT_ID,
6329 	.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,
6330 	.large_lock_type = 0,
6331 	.exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE,
6332 	.shared_lock_type = SMB2_LOCKFLAG_SHARED,
6333 	.unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
6334 	.header_size = sizeof(struct smb2_hdr),
6335 	.max_header_size = MAX_SMB2_HDR_SIZE,
6336 	.read_rsp_size = sizeof(struct smb2_read_rsp),
6337 	.lock_cmd = SMB2_LOCK,
6338 	.cap_unix = 0,
6339 	.cap_nt_find = SMB2_NT_FIND,
6340 	.cap_large_files = SMB2_LARGE_FILES,
6341 	.signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
6342 	.signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
6343 	.create_lease_size = sizeof(struct create_lease_v2),
6344 };
6345