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