• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: LGPL-2.1
2 /*
3  *
4  *   Copyright (C) International Business Machines  Corp., 2002,2008
5  *   Author(s): Steve French (sfrench@us.ibm.com)
6  *
7  */
8 
9 #include <linux/slab.h>
10 #include <linux/ctype.h>
11 #include <linux/mempool.h>
12 #include <linux/vmalloc.h>
13 #include "cifspdu.h"
14 #include "cifsglob.h"
15 #include "cifsproto.h"
16 #include "cifs_debug.h"
17 #include "smberr.h"
18 #include "nterr.h"
19 #include "cifs_unicode.h"
20 #include "smb2pdu.h"
21 #include "cifsfs.h"
22 #ifdef CONFIG_CIFS_DFS_UPCALL
23 #include "dns_resolve.h"
24 #endif
25 #include "fs_context.h"
26 
27 extern mempool_t *cifs_sm_req_poolp;
28 extern mempool_t *cifs_req_poolp;
29 
30 /* The xid serves as a useful identifier for each incoming vfs request,
31    in a similar way to the mid which is useful to track each sent smb,
32    and CurrentXid can also provide a running counter (although it
33    will eventually wrap past zero) of the total vfs operations handled
34    since the cifs fs was mounted */
35 
36 unsigned int
_get_xid(void)37 _get_xid(void)
38 {
39 	unsigned int xid;
40 
41 	spin_lock(&GlobalMid_Lock);
42 	GlobalTotalActiveXid++;
43 
44 	/* keep high water mark for number of simultaneous ops in filesystem */
45 	if (GlobalTotalActiveXid > GlobalMaxActiveXid)
46 		GlobalMaxActiveXid = GlobalTotalActiveXid;
47 	if (GlobalTotalActiveXid > 65000)
48 		cifs_dbg(FYI, "warning: more than 65000 requests active\n");
49 	xid = GlobalCurrentXid++;
50 	spin_unlock(&GlobalMid_Lock);
51 	return xid;
52 }
53 
54 void
_free_xid(unsigned int xid)55 _free_xid(unsigned int xid)
56 {
57 	spin_lock(&GlobalMid_Lock);
58 	/* if (GlobalTotalActiveXid == 0)
59 		BUG(); */
60 	GlobalTotalActiveXid--;
61 	spin_unlock(&GlobalMid_Lock);
62 }
63 
64 struct cifs_ses *
sesInfoAlloc(void)65 sesInfoAlloc(void)
66 {
67 	struct cifs_ses *ret_buf;
68 
69 	ret_buf = kzalloc(sizeof(struct cifs_ses), GFP_KERNEL);
70 	if (ret_buf) {
71 		atomic_inc(&sesInfoAllocCount);
72 		ret_buf->status = CifsNew;
73 		++ret_buf->ses_count;
74 		INIT_LIST_HEAD(&ret_buf->smb_ses_list);
75 		INIT_LIST_HEAD(&ret_buf->tcon_list);
76 		mutex_init(&ret_buf->session_mutex);
77 		spin_lock_init(&ret_buf->iface_lock);
78 		spin_lock_init(&ret_buf->chan_lock);
79 	}
80 	return ret_buf;
81 }
82 
83 void
sesInfoFree(struct cifs_ses * buf_to_free)84 sesInfoFree(struct cifs_ses *buf_to_free)
85 {
86 	if (buf_to_free == NULL) {
87 		cifs_dbg(FYI, "Null buffer passed to sesInfoFree\n");
88 		return;
89 	}
90 
91 	atomic_dec(&sesInfoAllocCount);
92 	kfree(buf_to_free->serverOS);
93 	kfree(buf_to_free->serverDomain);
94 	kfree(buf_to_free->serverNOS);
95 	kfree_sensitive(buf_to_free->password);
96 	kfree(buf_to_free->user_name);
97 	kfree(buf_to_free->domainName);
98 	kfree_sensitive(buf_to_free->auth_key.response);
99 	kfree(buf_to_free->iface_list);
100 	kfree_sensitive(buf_to_free);
101 }
102 
103 struct cifs_tcon *
tconInfoAlloc(void)104 tconInfoAlloc(void)
105 {
106 	struct cifs_tcon *ret_buf;
107 
108 	ret_buf = kzalloc(sizeof(*ret_buf), GFP_KERNEL);
109 	if (!ret_buf)
110 		return NULL;
111 	ret_buf->crfid.fid = kzalloc(sizeof(*ret_buf->crfid.fid), GFP_KERNEL);
112 	if (!ret_buf->crfid.fid) {
113 		kfree(ret_buf);
114 		return NULL;
115 	}
116 
117 	atomic_inc(&tconInfoAllocCount);
118 	ret_buf->tidStatus = CifsNew;
119 	++ret_buf->tc_count;
120 	INIT_LIST_HEAD(&ret_buf->openFileList);
121 	INIT_LIST_HEAD(&ret_buf->tcon_list);
122 	spin_lock_init(&ret_buf->open_file_lock);
123 	mutex_init(&ret_buf->crfid.fid_mutex);
124 	spin_lock_init(&ret_buf->stat_lock);
125 	atomic_set(&ret_buf->num_local_opens, 0);
126 	atomic_set(&ret_buf->num_remote_opens, 0);
127 
128 	return ret_buf;
129 }
130 
131 void
tconInfoFree(struct cifs_tcon * buf_to_free)132 tconInfoFree(struct cifs_tcon *buf_to_free)
133 {
134 	if (buf_to_free == NULL) {
135 		cifs_dbg(FYI, "Null buffer passed to tconInfoFree\n");
136 		return;
137 	}
138 	atomic_dec(&tconInfoAllocCount);
139 	kfree(buf_to_free->nativeFileSystem);
140 	kfree_sensitive(buf_to_free->password);
141 	kfree(buf_to_free->crfid.fid);
142 	kfree(buf_to_free);
143 }
144 
145 struct smb_hdr *
cifs_buf_get(void)146 cifs_buf_get(void)
147 {
148 	struct smb_hdr *ret_buf = NULL;
149 	/*
150 	 * SMB2 header is bigger than CIFS one - no problems to clean some
151 	 * more bytes for CIFS.
152 	 */
153 	size_t buf_size = sizeof(struct smb2_sync_hdr);
154 
155 	/*
156 	 * We could use negotiated size instead of max_msgsize -
157 	 * but it may be more efficient to always alloc same size
158 	 * albeit slightly larger than necessary and maxbuffersize
159 	 * defaults to this and can not be bigger.
160 	 */
161 	ret_buf = mempool_alloc(cifs_req_poolp, GFP_NOFS);
162 
163 	/* clear the first few header bytes */
164 	/* for most paths, more is cleared in header_assemble */
165 	memset(ret_buf, 0, buf_size + 3);
166 	atomic_inc(&bufAllocCount);
167 #ifdef CONFIG_CIFS_STATS2
168 	atomic_inc(&totBufAllocCount);
169 #endif /* CONFIG_CIFS_STATS2 */
170 
171 	return ret_buf;
172 }
173 
174 void
cifs_buf_release(void * buf_to_free)175 cifs_buf_release(void *buf_to_free)
176 {
177 	if (buf_to_free == NULL) {
178 		/* cifs_dbg(FYI, "Null buffer passed to cifs_buf_release\n");*/
179 		return;
180 	}
181 	mempool_free(buf_to_free, cifs_req_poolp);
182 
183 	atomic_dec(&bufAllocCount);
184 	return;
185 }
186 
187 struct smb_hdr *
cifs_small_buf_get(void)188 cifs_small_buf_get(void)
189 {
190 	struct smb_hdr *ret_buf = NULL;
191 
192 /* We could use negotiated size instead of max_msgsize -
193    but it may be more efficient to always alloc same size
194    albeit slightly larger than necessary and maxbuffersize
195    defaults to this and can not be bigger */
196 	ret_buf = mempool_alloc(cifs_sm_req_poolp, GFP_NOFS);
197 	/* No need to clear memory here, cleared in header assemble */
198 	/*	memset(ret_buf, 0, sizeof(struct smb_hdr) + 27);*/
199 	atomic_inc(&smBufAllocCount);
200 #ifdef CONFIG_CIFS_STATS2
201 	atomic_inc(&totSmBufAllocCount);
202 #endif /* CONFIG_CIFS_STATS2 */
203 
204 	return ret_buf;
205 }
206 
207 void
cifs_small_buf_release(void * buf_to_free)208 cifs_small_buf_release(void *buf_to_free)
209 {
210 
211 	if (buf_to_free == NULL) {
212 		cifs_dbg(FYI, "Null buffer passed to cifs_small_buf_release\n");
213 		return;
214 	}
215 	mempool_free(buf_to_free, cifs_sm_req_poolp);
216 
217 	atomic_dec(&smBufAllocCount);
218 	return;
219 }
220 
221 void
free_rsp_buf(int resp_buftype,void * rsp)222 free_rsp_buf(int resp_buftype, void *rsp)
223 {
224 	if (resp_buftype == CIFS_SMALL_BUFFER)
225 		cifs_small_buf_release(rsp);
226 	else if (resp_buftype == CIFS_LARGE_BUFFER)
227 		cifs_buf_release(rsp);
228 }
229 
230 /* NB: MID can not be set if treeCon not passed in, in that
231    case it is responsbility of caller to set the mid */
232 void
header_assemble(struct smb_hdr * buffer,char smb_command,const struct cifs_tcon * treeCon,int word_count)233 header_assemble(struct smb_hdr *buffer, char smb_command /* command */ ,
234 		const struct cifs_tcon *treeCon, int word_count
235 		/* length of fixed section (word count) in two byte units  */)
236 {
237 	char *temp = (char *) buffer;
238 
239 	memset(temp, 0, 256); /* bigger than MAX_CIFS_HDR_SIZE */
240 
241 	buffer->smb_buf_length = cpu_to_be32(
242 	    (2 * word_count) + sizeof(struct smb_hdr) -
243 	    4 /*  RFC 1001 length field does not count */  +
244 	    2 /* for bcc field itself */) ;
245 
246 	buffer->Protocol[0] = 0xFF;
247 	buffer->Protocol[1] = 'S';
248 	buffer->Protocol[2] = 'M';
249 	buffer->Protocol[3] = 'B';
250 	buffer->Command = smb_command;
251 	buffer->Flags = 0x00;	/* case sensitive */
252 	buffer->Flags2 = SMBFLG2_KNOWS_LONG_NAMES;
253 	buffer->Pid = cpu_to_le16((__u16)current->tgid);
254 	buffer->PidHigh = cpu_to_le16((__u16)(current->tgid >> 16));
255 	if (treeCon) {
256 		buffer->Tid = treeCon->tid;
257 		if (treeCon->ses) {
258 			if (treeCon->ses->capabilities & CAP_UNICODE)
259 				buffer->Flags2 |= SMBFLG2_UNICODE;
260 			if (treeCon->ses->capabilities & CAP_STATUS32)
261 				buffer->Flags2 |= SMBFLG2_ERR_STATUS;
262 
263 			/* Uid is not converted */
264 			buffer->Uid = treeCon->ses->Suid;
265 			if (treeCon->ses->server)
266 				buffer->Mid = get_next_mid(treeCon->ses->server);
267 		}
268 		if (treeCon->Flags & SMB_SHARE_IS_IN_DFS)
269 			buffer->Flags2 |= SMBFLG2_DFS;
270 		if (treeCon->nocase)
271 			buffer->Flags  |= SMBFLG_CASELESS;
272 		if ((treeCon->ses) && (treeCon->ses->server))
273 			if (treeCon->ses->server->sign)
274 				buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
275 	}
276 
277 /*  endian conversion of flags is now done just before sending */
278 	buffer->WordCount = (char) word_count;
279 	return;
280 }
281 
282 static int
check_smb_hdr(struct smb_hdr * smb)283 check_smb_hdr(struct smb_hdr *smb)
284 {
285 	/* does it have the right SMB "signature" ? */
286 	if (*(__le32 *) smb->Protocol != cpu_to_le32(0x424d53ff)) {
287 		cifs_dbg(VFS, "Bad protocol string signature header 0x%x\n",
288 			 *(unsigned int *)smb->Protocol);
289 		return 1;
290 	}
291 
292 	/* if it's a response then accept */
293 	if (smb->Flags & SMBFLG_RESPONSE)
294 		return 0;
295 
296 	/* only one valid case where server sends us request */
297 	if (smb->Command == SMB_COM_LOCKING_ANDX)
298 		return 0;
299 
300 	cifs_dbg(VFS, "Server sent request, not response. mid=%u\n",
301 		 get_mid(smb));
302 	return 1;
303 }
304 
305 int
checkSMB(char * buf,unsigned int total_read,struct TCP_Server_Info * server)306 checkSMB(char *buf, unsigned int total_read, struct TCP_Server_Info *server)
307 {
308 	struct smb_hdr *smb = (struct smb_hdr *)buf;
309 	__u32 rfclen = be32_to_cpu(smb->smb_buf_length);
310 	__u32 clc_len;  /* calculated length */
311 	cifs_dbg(FYI, "checkSMB Length: 0x%x, smb_buf_length: 0x%x\n",
312 		 total_read, rfclen);
313 
314 	/* is this frame too small to even get to a BCC? */
315 	if (total_read < 2 + sizeof(struct smb_hdr)) {
316 		if ((total_read >= sizeof(struct smb_hdr) - 1)
317 			    && (smb->Status.CifsError != 0)) {
318 			/* it's an error return */
319 			smb->WordCount = 0;
320 			/* some error cases do not return wct and bcc */
321 			return 0;
322 		} else if ((total_read == sizeof(struct smb_hdr) + 1) &&
323 				(smb->WordCount == 0)) {
324 			char *tmp = (char *)smb;
325 			/* Need to work around a bug in two servers here */
326 			/* First, check if the part of bcc they sent was zero */
327 			if (tmp[sizeof(struct smb_hdr)] == 0) {
328 				/* some servers return only half of bcc
329 				 * on simple responses (wct, bcc both zero)
330 				 * in particular have seen this on
331 				 * ulogoffX and FindClose. This leaves
332 				 * one byte of bcc potentially unitialized
333 				 */
334 				/* zero rest of bcc */
335 				tmp[sizeof(struct smb_hdr)+1] = 0;
336 				return 0;
337 			}
338 			cifs_dbg(VFS, "rcvd invalid byte count (bcc)\n");
339 		} else {
340 			cifs_dbg(VFS, "Length less than smb header size\n");
341 		}
342 		return -EIO;
343 	} else if (total_read < sizeof(*smb) + 2 * smb->WordCount) {
344 		cifs_dbg(VFS, "%s: can't read BCC due to invalid WordCount(%u)\n",
345 			 __func__, smb->WordCount);
346 		return -EIO;
347 	}
348 
349 	/* otherwise, there is enough to get to the BCC */
350 	if (check_smb_hdr(smb))
351 		return -EIO;
352 	clc_len = smbCalcSize(smb, server);
353 
354 	if (4 + rfclen != total_read) {
355 		cifs_dbg(VFS, "Length read does not match RFC1001 length %d\n",
356 			 rfclen);
357 		return -EIO;
358 	}
359 
360 	if (4 + rfclen != clc_len) {
361 		__u16 mid = get_mid(smb);
362 		/* check if bcc wrapped around for large read responses */
363 		if ((rfclen > 64 * 1024) && (rfclen > clc_len)) {
364 			/* check if lengths match mod 64K */
365 			if (((4 + rfclen) & 0xFFFF) == (clc_len & 0xFFFF))
366 				return 0; /* bcc wrapped */
367 		}
368 		cifs_dbg(FYI, "Calculated size %u vs length %u mismatch for mid=%u\n",
369 			 clc_len, 4 + rfclen, mid);
370 
371 		if (4 + rfclen < clc_len) {
372 			cifs_dbg(VFS, "RFC1001 size %u smaller than SMB for mid=%u\n",
373 				 rfclen, mid);
374 			return -EIO;
375 		} else if (rfclen > clc_len + 512) {
376 			/*
377 			 * Some servers (Windows XP in particular) send more
378 			 * data than the lengths in the SMB packet would
379 			 * indicate on certain calls (byte range locks and
380 			 * trans2 find first calls in particular). While the
381 			 * client can handle such a frame by ignoring the
382 			 * trailing data, we choose limit the amount of extra
383 			 * data to 512 bytes.
384 			 */
385 			cifs_dbg(VFS, "RFC1001 size %u more than 512 bytes larger than SMB for mid=%u\n",
386 				 rfclen, mid);
387 			return -EIO;
388 		}
389 	}
390 	return 0;
391 }
392 
393 bool
is_valid_oplock_break(char * buffer,struct TCP_Server_Info * srv)394 is_valid_oplock_break(char *buffer, struct TCP_Server_Info *srv)
395 {
396 	struct smb_hdr *buf = (struct smb_hdr *)buffer;
397 	struct smb_com_lock_req *pSMB = (struct smb_com_lock_req *)buf;
398 	struct list_head *tmp, *tmp1, *tmp2;
399 	struct cifs_ses *ses;
400 	struct cifs_tcon *tcon;
401 	struct cifsInodeInfo *pCifsInode;
402 	struct cifsFileInfo *netfile;
403 
404 	cifs_dbg(FYI, "Checking for oplock break or dnotify response\n");
405 	if ((pSMB->hdr.Command == SMB_COM_NT_TRANSACT) &&
406 	   (pSMB->hdr.Flags & SMBFLG_RESPONSE)) {
407 		struct smb_com_transaction_change_notify_rsp *pSMBr =
408 			(struct smb_com_transaction_change_notify_rsp *)buf;
409 		struct file_notify_information *pnotify;
410 		__u32 data_offset = 0;
411 		size_t len = srv->total_read - sizeof(pSMBr->hdr.smb_buf_length);
412 
413 		if (get_bcc(buf) > sizeof(struct file_notify_information)) {
414 			data_offset = le32_to_cpu(pSMBr->DataOffset);
415 
416 			if (data_offset >
417 			    len - sizeof(struct file_notify_information)) {
418 				cifs_dbg(FYI, "Invalid data_offset %u\n",
419 					 data_offset);
420 				return true;
421 			}
422 			pnotify = (struct file_notify_information *)
423 				((char *)&pSMBr->hdr.Protocol + data_offset);
424 			cifs_dbg(FYI, "dnotify on %s Action: 0x%x\n",
425 				 pnotify->FileName, pnotify->Action);
426 			/*   cifs_dump_mem("Rcvd notify Data: ",buf,
427 				sizeof(struct smb_hdr)+60); */
428 			return true;
429 		}
430 		if (pSMBr->hdr.Status.CifsError) {
431 			cifs_dbg(FYI, "notify err 0x%x\n",
432 				 pSMBr->hdr.Status.CifsError);
433 			return true;
434 		}
435 		return false;
436 	}
437 	if (pSMB->hdr.Command != SMB_COM_LOCKING_ANDX)
438 		return false;
439 	if (pSMB->hdr.Flags & SMBFLG_RESPONSE) {
440 		/* no sense logging error on invalid handle on oplock
441 		   break - harmless race between close request and oplock
442 		   break response is expected from time to time writing out
443 		   large dirty files cached on the client */
444 		if ((NT_STATUS_INVALID_HANDLE) ==
445 		   le32_to_cpu(pSMB->hdr.Status.CifsError)) {
446 			cifs_dbg(FYI, "Invalid handle on oplock break\n");
447 			return true;
448 		} else if (ERRbadfid ==
449 		   le16_to_cpu(pSMB->hdr.Status.DosError.Error)) {
450 			return true;
451 		} else {
452 			return false; /* on valid oplock brk we get "request" */
453 		}
454 	}
455 	if (pSMB->hdr.WordCount != 8)
456 		return false;
457 
458 	cifs_dbg(FYI, "oplock type 0x%x level 0x%x\n",
459 		 pSMB->LockType, pSMB->OplockLevel);
460 	if (!(pSMB->LockType & LOCKING_ANDX_OPLOCK_RELEASE))
461 		return false;
462 
463 	/* look up tcon based on tid & uid */
464 	spin_lock(&cifs_tcp_ses_lock);
465 	list_for_each(tmp, &srv->smb_ses_list) {
466 		ses = list_entry(tmp, struct cifs_ses, smb_ses_list);
467 		list_for_each(tmp1, &ses->tcon_list) {
468 			tcon = list_entry(tmp1, struct cifs_tcon, tcon_list);
469 			if (tcon->tid != buf->Tid)
470 				continue;
471 
472 			cifs_stats_inc(&tcon->stats.cifs_stats.num_oplock_brks);
473 			spin_lock(&tcon->open_file_lock);
474 			list_for_each(tmp2, &tcon->openFileList) {
475 				netfile = list_entry(tmp2, struct cifsFileInfo,
476 						     tlist);
477 				if (pSMB->Fid != netfile->fid.netfid)
478 					continue;
479 
480 				cifs_dbg(FYI, "file id match, oplock break\n");
481 				pCifsInode = CIFS_I(d_inode(netfile->dentry));
482 
483 				set_bit(CIFS_INODE_PENDING_OPLOCK_BREAK,
484 					&pCifsInode->flags);
485 
486 				netfile->oplock_epoch = 0;
487 				netfile->oplock_level = pSMB->OplockLevel;
488 				netfile->oplock_break_cancelled = false;
489 				cifs_queue_oplock_break(netfile);
490 
491 				spin_unlock(&tcon->open_file_lock);
492 				spin_unlock(&cifs_tcp_ses_lock);
493 				return true;
494 			}
495 			spin_unlock(&tcon->open_file_lock);
496 			spin_unlock(&cifs_tcp_ses_lock);
497 			cifs_dbg(FYI, "No matching file for oplock break\n");
498 			return true;
499 		}
500 	}
501 	spin_unlock(&cifs_tcp_ses_lock);
502 	cifs_dbg(FYI, "Can not process oplock break for non-existent connection\n");
503 	return true;
504 }
505 
506 void
dump_smb(void * buf,int smb_buf_length)507 dump_smb(void *buf, int smb_buf_length)
508 {
509 	if (traceSMB == 0)
510 		return;
511 
512 	print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_NONE, 8, 2, buf,
513 		       smb_buf_length, true);
514 }
515 
516 void
cifs_autodisable_serverino(struct cifs_sb_info * cifs_sb)517 cifs_autodisable_serverino(struct cifs_sb_info *cifs_sb)
518 {
519 	if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_SERVER_INUM) {
520 		struct cifs_tcon *tcon = NULL;
521 
522 		if (cifs_sb->master_tlink)
523 			tcon = cifs_sb_master_tcon(cifs_sb);
524 
525 		cifs_sb->mnt_cifs_flags &= ~CIFS_MOUNT_SERVER_INUM;
526 		cifs_sb->mnt_cifs_serverino_autodisabled = true;
527 		cifs_dbg(VFS, "Autodisabling the use of server inode numbers on %s\n",
528 			 tcon ? tcon->treeName : "new server");
529 		cifs_dbg(VFS, "The server doesn't seem to support them properly or the files might be on different servers (DFS)\n");
530 		cifs_dbg(VFS, "Hardlinks will not be recognized on this mount. Consider mounting with the \"noserverino\" option to silence this message.\n");
531 
532 	}
533 }
534 
cifs_set_oplock_level(struct cifsInodeInfo * cinode,__u32 oplock)535 void cifs_set_oplock_level(struct cifsInodeInfo *cinode, __u32 oplock)
536 {
537 	oplock &= 0xF;
538 
539 	if (oplock == OPLOCK_EXCLUSIVE) {
540 		cinode->oplock = CIFS_CACHE_WRITE_FLG | CIFS_CACHE_READ_FLG;
541 		cifs_dbg(FYI, "Exclusive Oplock granted on inode %p\n",
542 			 &cinode->vfs_inode);
543 	} else if (oplock == OPLOCK_READ) {
544 		cinode->oplock = CIFS_CACHE_READ_FLG;
545 		cifs_dbg(FYI, "Level II Oplock granted on inode %p\n",
546 			 &cinode->vfs_inode);
547 	} else
548 		cinode->oplock = 0;
549 }
550 
551 /*
552  * We wait for oplock breaks to be processed before we attempt to perform
553  * writes.
554  */
cifs_get_writer(struct cifsInodeInfo * cinode)555 int cifs_get_writer(struct cifsInodeInfo *cinode)
556 {
557 	int rc;
558 
559 start:
560 	rc = wait_on_bit(&cinode->flags, CIFS_INODE_PENDING_OPLOCK_BREAK,
561 			 TASK_KILLABLE);
562 	if (rc)
563 		return rc;
564 
565 	spin_lock(&cinode->writers_lock);
566 	if (!cinode->writers)
567 		set_bit(CIFS_INODE_PENDING_WRITERS, &cinode->flags);
568 	cinode->writers++;
569 	/* Check to see if we have started servicing an oplock break */
570 	if (test_bit(CIFS_INODE_PENDING_OPLOCK_BREAK, &cinode->flags)) {
571 		cinode->writers--;
572 		if (cinode->writers == 0) {
573 			clear_bit(CIFS_INODE_PENDING_WRITERS, &cinode->flags);
574 			wake_up_bit(&cinode->flags, CIFS_INODE_PENDING_WRITERS);
575 		}
576 		spin_unlock(&cinode->writers_lock);
577 		goto start;
578 	}
579 	spin_unlock(&cinode->writers_lock);
580 	return 0;
581 }
582 
cifs_put_writer(struct cifsInodeInfo * cinode)583 void cifs_put_writer(struct cifsInodeInfo *cinode)
584 {
585 	spin_lock(&cinode->writers_lock);
586 	cinode->writers--;
587 	if (cinode->writers == 0) {
588 		clear_bit(CIFS_INODE_PENDING_WRITERS, &cinode->flags);
589 		wake_up_bit(&cinode->flags, CIFS_INODE_PENDING_WRITERS);
590 	}
591 	spin_unlock(&cinode->writers_lock);
592 }
593 
594 /**
595  * cifs_queue_oplock_break - queue the oplock break handler for cfile
596  * @cfile: The file to break the oplock on
597  *
598  * This function is called from the demultiplex thread when it
599  * receives an oplock break for @cfile.
600  *
601  * Assumes the tcon->open_file_lock is held.
602  * Assumes cfile->file_info_lock is NOT held.
603  */
cifs_queue_oplock_break(struct cifsFileInfo * cfile)604 void cifs_queue_oplock_break(struct cifsFileInfo *cfile)
605 {
606 	/*
607 	 * Bump the handle refcount now while we hold the
608 	 * open_file_lock to enforce the validity of it for the oplock
609 	 * break handler. The matching put is done at the end of the
610 	 * handler.
611 	 */
612 	cifsFileInfo_get(cfile);
613 
614 	queue_work(cifsoplockd_wq, &cfile->oplock_break);
615 }
616 
cifs_done_oplock_break(struct cifsInodeInfo * cinode)617 void cifs_done_oplock_break(struct cifsInodeInfo *cinode)
618 {
619 	clear_bit(CIFS_INODE_PENDING_OPLOCK_BREAK, &cinode->flags);
620 	wake_up_bit(&cinode->flags, CIFS_INODE_PENDING_OPLOCK_BREAK);
621 }
622 
623 bool
backup_cred(struct cifs_sb_info * cifs_sb)624 backup_cred(struct cifs_sb_info *cifs_sb)
625 {
626 	if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_CIFS_BACKUPUID) {
627 		if (uid_eq(cifs_sb->ctx->backupuid, current_fsuid()))
628 			return true;
629 	}
630 	if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_CIFS_BACKUPGID) {
631 		if (in_group_p(cifs_sb->ctx->backupgid))
632 			return true;
633 	}
634 
635 	return false;
636 }
637 
638 void
cifs_del_pending_open(struct cifs_pending_open * open)639 cifs_del_pending_open(struct cifs_pending_open *open)
640 {
641 	spin_lock(&tlink_tcon(open->tlink)->open_file_lock);
642 	list_del(&open->olist);
643 	spin_unlock(&tlink_tcon(open->tlink)->open_file_lock);
644 }
645 
646 void
cifs_add_pending_open_locked(struct cifs_fid * fid,struct tcon_link * tlink,struct cifs_pending_open * open)647 cifs_add_pending_open_locked(struct cifs_fid *fid, struct tcon_link *tlink,
648 			     struct cifs_pending_open *open)
649 {
650 	memcpy(open->lease_key, fid->lease_key, SMB2_LEASE_KEY_SIZE);
651 	open->oplock = CIFS_OPLOCK_NO_CHANGE;
652 	open->tlink = tlink;
653 	fid->pending_open = open;
654 	list_add_tail(&open->olist, &tlink_tcon(tlink)->pending_opens);
655 }
656 
657 void
cifs_add_pending_open(struct cifs_fid * fid,struct tcon_link * tlink,struct cifs_pending_open * open)658 cifs_add_pending_open(struct cifs_fid *fid, struct tcon_link *tlink,
659 		      struct cifs_pending_open *open)
660 {
661 	spin_lock(&tlink_tcon(tlink)->open_file_lock);
662 	cifs_add_pending_open_locked(fid, tlink, open);
663 	spin_unlock(&tlink_tcon(open->tlink)->open_file_lock);
664 }
665 
666 /*
667  * Critical section which runs after acquiring deferred_lock.
668  * As there is no reference count on cifs_deferred_close, pdclose
669  * should not be used outside deferred_lock.
670  */
671 bool
cifs_is_deferred_close(struct cifsFileInfo * cfile,struct cifs_deferred_close ** pdclose)672 cifs_is_deferred_close(struct cifsFileInfo *cfile, struct cifs_deferred_close **pdclose)
673 {
674 	struct cifs_deferred_close *dclose;
675 
676 	list_for_each_entry(dclose, &CIFS_I(d_inode(cfile->dentry))->deferred_closes, dlist) {
677 		if ((dclose->netfid == cfile->fid.netfid) &&
678 			(dclose->persistent_fid == cfile->fid.persistent_fid) &&
679 			(dclose->volatile_fid == cfile->fid.volatile_fid)) {
680 			*pdclose = dclose;
681 			return true;
682 		}
683 	}
684 	return false;
685 }
686 
687 /*
688  * Critical section which runs after acquiring deferred_lock.
689  */
690 void
cifs_add_deferred_close(struct cifsFileInfo * cfile,struct cifs_deferred_close * dclose)691 cifs_add_deferred_close(struct cifsFileInfo *cfile, struct cifs_deferred_close *dclose)
692 {
693 	bool is_deferred = false;
694 	struct cifs_deferred_close *pdclose;
695 
696 	is_deferred = cifs_is_deferred_close(cfile, &pdclose);
697 	if (is_deferred) {
698 		kfree(dclose);
699 		return;
700 	}
701 
702 	dclose->tlink = cfile->tlink;
703 	dclose->netfid = cfile->fid.netfid;
704 	dclose->persistent_fid = cfile->fid.persistent_fid;
705 	dclose->volatile_fid = cfile->fid.volatile_fid;
706 	list_add_tail(&dclose->dlist, &CIFS_I(d_inode(cfile->dentry))->deferred_closes);
707 }
708 
709 /*
710  * Critical section which runs after acquiring deferred_lock.
711  */
712 void
cifs_del_deferred_close(struct cifsFileInfo * cfile)713 cifs_del_deferred_close(struct cifsFileInfo *cfile)
714 {
715 	bool is_deferred = false;
716 	struct cifs_deferred_close *dclose;
717 
718 	is_deferred = cifs_is_deferred_close(cfile, &dclose);
719 	if (!is_deferred)
720 		return;
721 	list_del(&dclose->dlist);
722 	kfree(dclose);
723 }
724 
725 void
cifs_close_deferred_file(struct cifsInodeInfo * cifs_inode)726 cifs_close_deferred_file(struct cifsInodeInfo *cifs_inode)
727 {
728 	struct cifsFileInfo *cfile = NULL;
729 	struct file_list *tmp_list, *tmp_next_list;
730 	struct list_head file_head;
731 
732 	if (cifs_inode == NULL)
733 		return;
734 
735 	INIT_LIST_HEAD(&file_head);
736 	spin_lock(&cifs_inode->open_file_lock);
737 	list_for_each_entry(cfile, &cifs_inode->openFileList, flist) {
738 		if (delayed_work_pending(&cfile->deferred)) {
739 			if (cancel_delayed_work(&cfile->deferred)) {
740 				spin_lock(&cifs_inode->deferred_lock);
741 				cifs_del_deferred_close(cfile);
742 				spin_unlock(&cifs_inode->deferred_lock);
743 
744 				tmp_list = kmalloc(sizeof(struct file_list), GFP_ATOMIC);
745 				if (tmp_list == NULL)
746 					break;
747 				tmp_list->cfile = cfile;
748 				list_add_tail(&tmp_list->list, &file_head);
749 			}
750 		}
751 	}
752 	spin_unlock(&cifs_inode->open_file_lock);
753 
754 	list_for_each_entry_safe(tmp_list, tmp_next_list, &file_head, list) {
755 		_cifsFileInfo_put(tmp_list->cfile, false, false);
756 		list_del(&tmp_list->list);
757 		kfree(tmp_list);
758 	}
759 }
760 
761 void
cifs_close_all_deferred_files(struct cifs_tcon * tcon)762 cifs_close_all_deferred_files(struct cifs_tcon *tcon)
763 {
764 	struct cifsFileInfo *cfile;
765 	struct list_head *tmp;
766 	struct file_list *tmp_list, *tmp_next_list;
767 	struct list_head file_head;
768 
769 	INIT_LIST_HEAD(&file_head);
770 	spin_lock(&tcon->open_file_lock);
771 	list_for_each(tmp, &tcon->openFileList) {
772 		cfile = list_entry(tmp, struct cifsFileInfo, tlist);
773 		if (delayed_work_pending(&cfile->deferred)) {
774 			if (cancel_delayed_work(&cfile->deferred)) {
775 				spin_lock(&CIFS_I(d_inode(cfile->dentry))->deferred_lock);
776 				cifs_del_deferred_close(cfile);
777 				spin_unlock(&CIFS_I(d_inode(cfile->dentry))->deferred_lock);
778 
779 				tmp_list = kmalloc(sizeof(struct file_list), GFP_ATOMIC);
780 				if (tmp_list == NULL)
781 					break;
782 				tmp_list->cfile = cfile;
783 				list_add_tail(&tmp_list->list, &file_head);
784 			}
785 		}
786 	}
787 	spin_unlock(&tcon->open_file_lock);
788 
789 	list_for_each_entry_safe(tmp_list, tmp_next_list, &file_head, list) {
790 		_cifsFileInfo_put(tmp_list->cfile, true, false);
791 		list_del(&tmp_list->list);
792 		kfree(tmp_list);
793 	}
794 }
795 void
cifs_close_deferred_file_under_dentry(struct cifs_tcon * tcon,const char * path)796 cifs_close_deferred_file_under_dentry(struct cifs_tcon *tcon, const char *path)
797 {
798 	struct cifsFileInfo *cfile;
799 	struct list_head *tmp;
800 	struct file_list *tmp_list, *tmp_next_list;
801 	struct list_head file_head;
802 	void *page;
803 	const char *full_path;
804 
805 	INIT_LIST_HEAD(&file_head);
806 	page = alloc_dentry_path();
807 	spin_lock(&tcon->open_file_lock);
808 	list_for_each(tmp, &tcon->openFileList) {
809 		cfile = list_entry(tmp, struct cifsFileInfo, tlist);
810 		full_path = build_path_from_dentry(cfile->dentry, page);
811 		if (strstr(full_path, path)) {
812 			if (delayed_work_pending(&cfile->deferred)) {
813 				if (cancel_delayed_work(&cfile->deferred)) {
814 					spin_lock(&CIFS_I(d_inode(cfile->dentry))->deferred_lock);
815 					cifs_del_deferred_close(cfile);
816 					spin_unlock(&CIFS_I(d_inode(cfile->dentry))->deferred_lock);
817 
818 					tmp_list = kmalloc(sizeof(struct file_list), GFP_ATOMIC);
819 					if (tmp_list == NULL)
820 						break;
821 					tmp_list->cfile = cfile;
822 					list_add_tail(&tmp_list->list, &file_head);
823 				}
824 			}
825 		}
826 	}
827 	spin_unlock(&tcon->open_file_lock);
828 
829 	list_for_each_entry_safe(tmp_list, tmp_next_list, &file_head, list) {
830 		_cifsFileInfo_put(tmp_list->cfile, true, false);
831 		list_del(&tmp_list->list);
832 		kfree(tmp_list);
833 	}
834 	free_dentry_path(page);
835 }
836 
837 /* parses DFS refferal V3 structure
838  * caller is responsible for freeing target_nodes
839  * returns:
840  * - on success - 0
841  * - on failure - errno
842  */
843 int
parse_dfs_referrals(struct get_dfs_referral_rsp * rsp,u32 rsp_size,unsigned int * num_of_nodes,struct dfs_info3_param ** target_nodes,const struct nls_table * nls_codepage,int remap,const char * searchName,bool is_unicode)844 parse_dfs_referrals(struct get_dfs_referral_rsp *rsp, u32 rsp_size,
845 		    unsigned int *num_of_nodes,
846 		    struct dfs_info3_param **target_nodes,
847 		    const struct nls_table *nls_codepage, int remap,
848 		    const char *searchName, bool is_unicode)
849 {
850 	int i, rc = 0;
851 	char *data_end;
852 	struct dfs_referral_level_3 *ref;
853 
854 	*num_of_nodes = le16_to_cpu(rsp->NumberOfReferrals);
855 
856 	if (*num_of_nodes < 1) {
857 		cifs_dbg(VFS, "num_referrals: must be at least > 0, but we get num_referrals = %d\n",
858 			 *num_of_nodes);
859 		rc = -EINVAL;
860 		goto parse_DFS_referrals_exit;
861 	}
862 
863 	ref = (struct dfs_referral_level_3 *) &(rsp->referrals);
864 	if (ref->VersionNumber != cpu_to_le16(3)) {
865 		cifs_dbg(VFS, "Referrals of V%d version are not supported, should be V3\n",
866 			 le16_to_cpu(ref->VersionNumber));
867 		rc = -EINVAL;
868 		goto parse_DFS_referrals_exit;
869 	}
870 
871 	/* get the upper boundary of the resp buffer */
872 	data_end = (char *)rsp + rsp_size;
873 
874 	cifs_dbg(FYI, "num_referrals: %d dfs flags: 0x%x ...\n",
875 		 *num_of_nodes, le32_to_cpu(rsp->DFSFlags));
876 
877 	*target_nodes = kcalloc(*num_of_nodes, sizeof(struct dfs_info3_param),
878 				GFP_KERNEL);
879 	if (*target_nodes == NULL) {
880 		rc = -ENOMEM;
881 		goto parse_DFS_referrals_exit;
882 	}
883 
884 	/* collect necessary data from referrals */
885 	for (i = 0; i < *num_of_nodes; i++) {
886 		char *temp;
887 		int max_len;
888 		struct dfs_info3_param *node = (*target_nodes)+i;
889 
890 		node->flags = le32_to_cpu(rsp->DFSFlags);
891 		if (is_unicode) {
892 			__le16 *tmp = kmalloc(strlen(searchName)*2 + 2,
893 						GFP_KERNEL);
894 			if (tmp == NULL) {
895 				rc = -ENOMEM;
896 				goto parse_DFS_referrals_exit;
897 			}
898 			cifsConvertToUTF16((__le16 *) tmp, searchName,
899 					   PATH_MAX, nls_codepage, remap);
900 			node->path_consumed = cifs_utf16_bytes(tmp,
901 					le16_to_cpu(rsp->PathConsumed),
902 					nls_codepage);
903 			kfree(tmp);
904 		} else
905 			node->path_consumed = le16_to_cpu(rsp->PathConsumed);
906 
907 		node->server_type = le16_to_cpu(ref->ServerType);
908 		node->ref_flag = le16_to_cpu(ref->ReferralEntryFlags);
909 
910 		/* copy DfsPath */
911 		temp = (char *)ref + le16_to_cpu(ref->DfsPathOffset);
912 		max_len = data_end - temp;
913 		node->path_name = cifs_strndup_from_utf16(temp, max_len,
914 						is_unicode, nls_codepage);
915 		if (!node->path_name) {
916 			rc = -ENOMEM;
917 			goto parse_DFS_referrals_exit;
918 		}
919 
920 		/* copy link target UNC */
921 		temp = (char *)ref + le16_to_cpu(ref->NetworkAddressOffset);
922 		max_len = data_end - temp;
923 		node->node_name = cifs_strndup_from_utf16(temp, max_len,
924 						is_unicode, nls_codepage);
925 		if (!node->node_name) {
926 			rc = -ENOMEM;
927 			goto parse_DFS_referrals_exit;
928 		}
929 
930 		node->ttl = le32_to_cpu(ref->TimeToLive);
931 
932 		ref++;
933 	}
934 
935 parse_DFS_referrals_exit:
936 	if (rc) {
937 		free_dfs_info_array(*target_nodes, *num_of_nodes);
938 		*target_nodes = NULL;
939 		*num_of_nodes = 0;
940 	}
941 	return rc;
942 }
943 
944 struct cifs_aio_ctx *
cifs_aio_ctx_alloc(void)945 cifs_aio_ctx_alloc(void)
946 {
947 	struct cifs_aio_ctx *ctx;
948 
949 	/*
950 	 * Must use kzalloc to initialize ctx->bv to NULL and ctx->direct_io
951 	 * to false so that we know when we have to unreference pages within
952 	 * cifs_aio_ctx_release()
953 	 */
954 	ctx = kzalloc(sizeof(struct cifs_aio_ctx), GFP_KERNEL);
955 	if (!ctx)
956 		return NULL;
957 
958 	INIT_LIST_HEAD(&ctx->list);
959 	mutex_init(&ctx->aio_mutex);
960 	init_completion(&ctx->done);
961 	kref_init(&ctx->refcount);
962 	return ctx;
963 }
964 
965 void
cifs_aio_ctx_release(struct kref * refcount)966 cifs_aio_ctx_release(struct kref *refcount)
967 {
968 	struct cifs_aio_ctx *ctx = container_of(refcount,
969 					struct cifs_aio_ctx, refcount);
970 
971 	cifsFileInfo_put(ctx->cfile);
972 
973 	/*
974 	 * ctx->bv is only set if setup_aio_ctx_iter() was call successfuly
975 	 * which means that iov_iter_get_pages() was a success and thus that
976 	 * we have taken reference on pages.
977 	 */
978 	if (ctx->bv) {
979 		unsigned i;
980 
981 		for (i = 0; i < ctx->npages; i++) {
982 			if (ctx->should_dirty)
983 				set_page_dirty(ctx->bv[i].bv_page);
984 			put_page(ctx->bv[i].bv_page);
985 		}
986 		kvfree(ctx->bv);
987 	}
988 
989 	kfree(ctx);
990 }
991 
992 #define CIFS_AIO_KMALLOC_LIMIT (1024 * 1024)
993 
994 int
setup_aio_ctx_iter(struct cifs_aio_ctx * ctx,struct iov_iter * iter,int rw)995 setup_aio_ctx_iter(struct cifs_aio_ctx *ctx, struct iov_iter *iter, int rw)
996 {
997 	ssize_t rc;
998 	unsigned int cur_npages;
999 	unsigned int npages = 0;
1000 	unsigned int i;
1001 	size_t len;
1002 	size_t count = iov_iter_count(iter);
1003 	unsigned int saved_len;
1004 	size_t start;
1005 	unsigned int max_pages = iov_iter_npages(iter, INT_MAX);
1006 	struct page **pages = NULL;
1007 	struct bio_vec *bv = NULL;
1008 
1009 	if (iov_iter_is_kvec(iter)) {
1010 		memcpy(&ctx->iter, iter, sizeof(*iter));
1011 		ctx->len = count;
1012 		iov_iter_advance(iter, count);
1013 		return 0;
1014 	}
1015 
1016 	if (array_size(max_pages, sizeof(*bv)) <= CIFS_AIO_KMALLOC_LIMIT)
1017 		bv = kmalloc_array(max_pages, sizeof(*bv), GFP_KERNEL);
1018 
1019 	if (!bv) {
1020 		bv = vmalloc(array_size(max_pages, sizeof(*bv)));
1021 		if (!bv)
1022 			return -ENOMEM;
1023 	}
1024 
1025 	if (array_size(max_pages, sizeof(*pages)) <= CIFS_AIO_KMALLOC_LIMIT)
1026 		pages = kmalloc_array(max_pages, sizeof(*pages), GFP_KERNEL);
1027 
1028 	if (!pages) {
1029 		pages = vmalloc(array_size(max_pages, sizeof(*pages)));
1030 		if (!pages) {
1031 			kvfree(bv);
1032 			return -ENOMEM;
1033 		}
1034 	}
1035 
1036 	saved_len = count;
1037 
1038 	while (count && npages < max_pages) {
1039 		rc = iov_iter_get_pages(iter, pages, count, max_pages, &start);
1040 		if (rc < 0) {
1041 			cifs_dbg(VFS, "Couldn't get user pages (rc=%zd)\n", rc);
1042 			break;
1043 		}
1044 
1045 		if (rc > count) {
1046 			cifs_dbg(VFS, "get pages rc=%zd more than %zu\n", rc,
1047 				 count);
1048 			break;
1049 		}
1050 
1051 		iov_iter_advance(iter, rc);
1052 		count -= rc;
1053 		rc += start;
1054 		cur_npages = DIV_ROUND_UP(rc, PAGE_SIZE);
1055 
1056 		if (npages + cur_npages > max_pages) {
1057 			cifs_dbg(VFS, "out of vec array capacity (%u vs %u)\n",
1058 				 npages + cur_npages, max_pages);
1059 			break;
1060 		}
1061 
1062 		for (i = 0; i < cur_npages; i++) {
1063 			len = rc > PAGE_SIZE ? PAGE_SIZE : rc;
1064 			bv[npages + i].bv_page = pages[i];
1065 			bv[npages + i].bv_offset = start;
1066 			bv[npages + i].bv_len = len - start;
1067 			rc -= len;
1068 			start = 0;
1069 		}
1070 
1071 		npages += cur_npages;
1072 	}
1073 
1074 	kvfree(pages);
1075 	ctx->bv = bv;
1076 	ctx->len = saved_len - count;
1077 	ctx->npages = npages;
1078 	iov_iter_bvec(&ctx->iter, rw, ctx->bv, npages, ctx->len);
1079 	return 0;
1080 }
1081 
1082 /**
1083  * cifs_alloc_hash - allocate hash and hash context together
1084  * @name: The name of the crypto hash algo
1085  * @shash: Where to put the pointer to the hash algo
1086  * @sdesc: Where to put the pointer to the hash descriptor
1087  *
1088  * The caller has to make sure @sdesc is initialized to either NULL or
1089  * a valid context. Both can be freed via cifs_free_hash().
1090  */
1091 int
cifs_alloc_hash(const char * name,struct crypto_shash ** shash,struct sdesc ** sdesc)1092 cifs_alloc_hash(const char *name,
1093 		struct crypto_shash **shash, struct sdesc **sdesc)
1094 {
1095 	int rc = 0;
1096 	size_t size;
1097 
1098 	if (*sdesc != NULL)
1099 		return 0;
1100 
1101 	*shash = crypto_alloc_shash(name, 0, 0);
1102 	if (IS_ERR(*shash)) {
1103 		cifs_dbg(VFS, "Could not allocate crypto %s\n", name);
1104 		rc = PTR_ERR(*shash);
1105 		*shash = NULL;
1106 		*sdesc = NULL;
1107 		return rc;
1108 	}
1109 
1110 	size = sizeof(struct shash_desc) + crypto_shash_descsize(*shash);
1111 	*sdesc = kmalloc(size, GFP_KERNEL);
1112 	if (*sdesc == NULL) {
1113 		cifs_dbg(VFS, "no memory left to allocate crypto %s\n", name);
1114 		crypto_free_shash(*shash);
1115 		*shash = NULL;
1116 		return -ENOMEM;
1117 	}
1118 
1119 	(*sdesc)->shash.tfm = *shash;
1120 	return 0;
1121 }
1122 
1123 /**
1124  * cifs_free_hash - free hash and hash context together
1125  * @shash: Where to find the pointer to the hash algo
1126  * @sdesc: Where to find the pointer to the hash descriptor
1127  *
1128  * Freeing a NULL hash or context is safe.
1129  */
1130 void
cifs_free_hash(struct crypto_shash ** shash,struct sdesc ** sdesc)1131 cifs_free_hash(struct crypto_shash **shash, struct sdesc **sdesc)
1132 {
1133 	kfree(*sdesc);
1134 	*sdesc = NULL;
1135 	if (*shash)
1136 		crypto_free_shash(*shash);
1137 	*shash = NULL;
1138 }
1139 
1140 /**
1141  * rqst_page_get_length - obtain the length and offset for a page in smb_rqst
1142  * @rqst: The request descriptor
1143  * @page: The index of the page to query
1144  * @len: Where to store the length for this page:
1145  * @offset: Where to store the offset for this page
1146  */
rqst_page_get_length(const struct smb_rqst * rqst,unsigned int page,unsigned int * len,unsigned int * offset)1147 void rqst_page_get_length(const struct smb_rqst *rqst, unsigned int page,
1148 			  unsigned int *len, unsigned int *offset)
1149 {
1150 	*len = rqst->rq_pagesz;
1151 	*offset = (page == 0) ? rqst->rq_offset : 0;
1152 
1153 	if (rqst->rq_npages == 1 || page == rqst->rq_npages-1)
1154 		*len = rqst->rq_tailsz;
1155 	else if (page == 0)
1156 		*len = rqst->rq_pagesz - rqst->rq_offset;
1157 }
1158 
extract_unc_hostname(const char * unc,const char ** h,size_t * len)1159 void extract_unc_hostname(const char *unc, const char **h, size_t *len)
1160 {
1161 	const char *end;
1162 
1163 	/* skip initial slashes */
1164 	while (*unc && (*unc == '\\' || *unc == '/'))
1165 		unc++;
1166 
1167 	end = unc;
1168 
1169 	while (*end && !(*end == '\\' || *end == '/'))
1170 		end++;
1171 
1172 	*h = unc;
1173 	*len = end - unc;
1174 }
1175 
1176 /**
1177  * copy_path_name - copy src path to dst, possibly truncating
1178  * @dst: The destination buffer
1179  * @src: The source name
1180  *
1181  * returns number of bytes written (including trailing nul)
1182  */
copy_path_name(char * dst,const char * src)1183 int copy_path_name(char *dst, const char *src)
1184 {
1185 	int name_len;
1186 
1187 	/*
1188 	 * PATH_MAX includes nul, so if strlen(src) >= PATH_MAX it
1189 	 * will truncate and strlen(dst) will be PATH_MAX-1
1190 	 */
1191 	name_len = strscpy(dst, src, PATH_MAX);
1192 	if (WARN_ON_ONCE(name_len < 0))
1193 		name_len = PATH_MAX-1;
1194 
1195 	/* we count the trailing nul */
1196 	name_len++;
1197 	return name_len;
1198 }
1199 
1200 struct super_cb_data {
1201 	void *data;
1202 	struct super_block *sb;
1203 };
1204 
tcp_super_cb(struct super_block * sb,void * arg)1205 static void tcp_super_cb(struct super_block *sb, void *arg)
1206 {
1207 	struct super_cb_data *sd = arg;
1208 	struct TCP_Server_Info *server = sd->data;
1209 	struct cifs_sb_info *cifs_sb;
1210 	struct cifs_tcon *tcon;
1211 
1212 	if (sd->sb)
1213 		return;
1214 
1215 	cifs_sb = CIFS_SB(sb);
1216 	tcon = cifs_sb_master_tcon(cifs_sb);
1217 	if (tcon->ses->server == server)
1218 		sd->sb = sb;
1219 }
1220 
__cifs_get_super(void (* f)(struct super_block *,void *),void * data)1221 static struct super_block *__cifs_get_super(void (*f)(struct super_block *, void *),
1222 					    void *data)
1223 {
1224 	struct super_cb_data sd = {
1225 		.data = data,
1226 		.sb = NULL,
1227 	};
1228 	struct file_system_type **fs_type = (struct file_system_type *[]) {
1229 		&cifs_fs_type, &smb3_fs_type, NULL,
1230 	};
1231 
1232 	for (; *fs_type; fs_type++) {
1233 		iterate_supers_type(*fs_type, f, &sd);
1234 		if (sd.sb) {
1235 			/*
1236 			 * Grab an active reference in order to prevent automounts (DFS links)
1237 			 * of expiring and then freeing up our cifs superblock pointer while
1238 			 * we're doing failover.
1239 			 */
1240 			cifs_sb_active(sd.sb);
1241 			return sd.sb;
1242 		}
1243 	}
1244 	return ERR_PTR(-EINVAL);
1245 }
1246 
__cifs_put_super(struct super_block * sb)1247 static void __cifs_put_super(struct super_block *sb)
1248 {
1249 	if (!IS_ERR_OR_NULL(sb))
1250 		cifs_sb_deactive(sb);
1251 }
1252 
cifs_get_tcp_super(struct TCP_Server_Info * server)1253 struct super_block *cifs_get_tcp_super(struct TCP_Server_Info *server)
1254 {
1255 	return __cifs_get_super(tcp_super_cb, server);
1256 }
1257 
cifs_put_tcp_super(struct super_block * sb)1258 void cifs_put_tcp_super(struct super_block *sb)
1259 {
1260 	__cifs_put_super(sb);
1261 }
1262 
1263 #ifdef CONFIG_CIFS_DFS_UPCALL
match_target_ip(struct TCP_Server_Info * server,const char * share,size_t share_len,bool * result)1264 int match_target_ip(struct TCP_Server_Info *server,
1265 		    const char *share, size_t share_len,
1266 		    bool *result)
1267 {
1268 	int rc;
1269 	char *target, *tip = NULL;
1270 	struct sockaddr tipaddr;
1271 
1272 	*result = false;
1273 
1274 	target = kzalloc(share_len + 3, GFP_KERNEL);
1275 	if (!target) {
1276 		rc = -ENOMEM;
1277 		goto out;
1278 	}
1279 
1280 	scnprintf(target, share_len + 3, "\\\\%.*s", (int)share_len, share);
1281 
1282 	cifs_dbg(FYI, "%s: target name: %s\n", __func__, target + 2);
1283 
1284 	rc = dns_resolve_server_name_to_ip(target, &tip, NULL);
1285 	if (rc < 0)
1286 		goto out;
1287 
1288 	cifs_dbg(FYI, "%s: target ip: %s\n", __func__, tip);
1289 
1290 	if (!cifs_convert_address(&tipaddr, tip, strlen(tip))) {
1291 		cifs_dbg(VFS, "%s: failed to convert target ip address\n",
1292 			 __func__);
1293 		rc = -EINVAL;
1294 		goto out;
1295 	}
1296 
1297 	*result = cifs_match_ipaddr((struct sockaddr *)&server->dstaddr,
1298 				    &tipaddr);
1299 	cifs_dbg(FYI, "%s: ip addresses match: %u\n", __func__, *result);
1300 	rc = 0;
1301 
1302 out:
1303 	kfree(target);
1304 	kfree(tip);
1305 
1306 	return rc;
1307 }
1308 
cifs_update_super_prepath(struct cifs_sb_info * cifs_sb,char * prefix)1309 int cifs_update_super_prepath(struct cifs_sb_info *cifs_sb, char *prefix)
1310 {
1311 	kfree(cifs_sb->prepath);
1312 
1313 	if (prefix && *prefix) {
1314 		cifs_sb->prepath = cifs_sanitize_prepath(prefix, GFP_ATOMIC);
1315 		if (!cifs_sb->prepath)
1316 			return -ENOMEM;
1317 
1318 		convert_delimiter(cifs_sb->prepath, CIFS_DIR_SEP(cifs_sb));
1319 	} else
1320 		cifs_sb->prepath = NULL;
1321 
1322 	cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
1323 	return 0;
1324 }
1325 #endif
1326