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