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