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