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