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