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