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