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