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