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