xref: /linux/fs/smb/client/misc.c (revision 69050f8d6d075dc01af7a5f2f550a8067510366f)
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 "cifsglob.h"
14 #include "cifsproto.h"
15 #include "cifs_debug.h"
16 #include "smberr.h"
17 #include "nterr.h"
18 #include "cifs_unicode.h"
19 #include "smb2pdu.h"
20 #include "smb2proto.h"
21 #include "smb1proto.h"
22 #include "cifsfs.h"
23 #ifdef CONFIG_CIFS_DFS_UPCALL
24 #include "dns_resolve.h"
25 #include "dfs_cache.h"
26 #include "dfs.h"
27 #endif
28 #include "fs_context.h"
29 #include "cached_dir.h"
30 
31 /* The xid serves as a useful identifier for each incoming vfs request,
32    in a similar way to the mid which is useful to track each sent smb,
33    and CurrentXid can also provide a running counter (although it
34    will eventually wrap past zero) of the total vfs operations handled
35    since the cifs fs was mounted */
36 
37 unsigned int
38 _get_xid(void)
39 {
40 	unsigned int xid;
41 
42 	spin_lock(&GlobalMid_Lock);
43 	GlobalTotalActiveXid++;
44 
45 	/* keep high water mark for number of simultaneous ops in filesystem */
46 	if (GlobalTotalActiveXid > GlobalMaxActiveXid)
47 		GlobalMaxActiveXid = GlobalTotalActiveXid;
48 	if (GlobalTotalActiveXid > 65000)
49 		cifs_dbg(FYI, "warning: more than 65000 requests active\n");
50 	xid = GlobalCurrentXid++;
51 	spin_unlock(&GlobalMid_Lock);
52 	return xid;
53 }
54 
55 void
56 _free_xid(unsigned int xid)
57 {
58 	spin_lock(&GlobalMid_Lock);
59 	/* if (GlobalTotalActiveXid == 0)
60 		BUG(); */
61 	GlobalTotalActiveXid--;
62 	spin_unlock(&GlobalMid_Lock);
63 }
64 
65 struct cifs_ses *
66 sesInfoAlloc(void)
67 {
68 	struct cifs_ses *ret_buf;
69 
70 	ret_buf = kzalloc_obj(struct cifs_ses, GFP_KERNEL);
71 	if (ret_buf) {
72 		atomic_inc(&sesInfoAllocCount);
73 		spin_lock_init(&ret_buf->ses_lock);
74 		ret_buf->ses_status = SES_NEW;
75 		++ret_buf->ses_count;
76 		INIT_LIST_HEAD(&ret_buf->smb_ses_list);
77 		INIT_LIST_HEAD(&ret_buf->tcon_list);
78 		mutex_init(&ret_buf->session_mutex);
79 		spin_lock_init(&ret_buf->iface_lock);
80 		INIT_LIST_HEAD(&ret_buf->iface_list);
81 		spin_lock_init(&ret_buf->chan_lock);
82 	}
83 	return ret_buf;
84 }
85 
86 void
87 sesInfoFree(struct cifs_ses *buf_to_free)
88 {
89 	struct cifs_server_iface *iface = NULL, *niface = NULL;
90 
91 	if (buf_to_free == NULL) {
92 		cifs_dbg(FYI, "Null buffer passed to sesInfoFree\n");
93 		return;
94 	}
95 
96 	unload_nls(buf_to_free->local_nls);
97 	atomic_dec(&sesInfoAllocCount);
98 	kfree(buf_to_free->serverOS);
99 	kfree(buf_to_free->serverDomain);
100 	kfree(buf_to_free->serverNOS);
101 	kfree_sensitive(buf_to_free->password);
102 	kfree_sensitive(buf_to_free->password2);
103 	kfree(buf_to_free->user_name);
104 	kfree(buf_to_free->domainName);
105 	kfree(buf_to_free->dns_dom);
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, enum smb3_tcon_ref_trace trace)
117 {
118 	struct cifs_tcon *ret_buf;
119 	static atomic_t tcon_debug_id;
120 
121 	ret_buf = kzalloc_obj(*ret_buf, GFP_KERNEL);
122 	if (!ret_buf)
123 		return NULL;
124 
125 	if (dir_leases_enabled == true) {
126 		ret_buf->cfids = init_cached_dirs();
127 		if (!ret_buf->cfids) {
128 			kfree(ret_buf);
129 			return NULL;
130 		}
131 	}
132 	/* else ret_buf->cfids is already set to NULL above */
133 
134 	atomic_inc(&tconInfoAllocCount);
135 	ret_buf->status = TID_NEW;
136 	ret_buf->debug_id = atomic_inc_return(&tcon_debug_id);
137 	ret_buf->tc_count = 1;
138 	spin_lock_init(&ret_buf->tc_lock);
139 	INIT_LIST_HEAD(&ret_buf->openFileList);
140 	INIT_LIST_HEAD(&ret_buf->tcon_list);
141 	INIT_LIST_HEAD(&ret_buf->cifs_sb_list);
142 	spin_lock_init(&ret_buf->open_file_lock);
143 	spin_lock_init(&ret_buf->stat_lock);
144 	spin_lock_init(&ret_buf->sb_list_lock);
145 	atomic_set(&ret_buf->num_local_opens, 0);
146 	atomic_set(&ret_buf->num_remote_opens, 0);
147 	ret_buf->stats_from_time = ktime_get_real_seconds();
148 #ifdef CONFIG_CIFS_FSCACHE
149 	mutex_init(&ret_buf->fscache_lock);
150 #endif
151 	trace_smb3_tcon_ref(ret_buf->debug_id, ret_buf->tc_count, trace);
152 #ifdef CONFIG_CIFS_DFS_UPCALL
153 	INIT_LIST_HEAD(&ret_buf->dfs_ses_list);
154 #endif
155 	INIT_LIST_HEAD(&ret_buf->pending_opens);
156 	INIT_DELAYED_WORK(&ret_buf->query_interfaces,
157 			  smb2_query_server_interfaces);
158 #ifdef CONFIG_CIFS_DFS_UPCALL
159 	INIT_DELAYED_WORK(&ret_buf->dfs_cache_work, dfs_cache_refresh);
160 #endif
161 
162 	return ret_buf;
163 }
164 
165 void
166 tconInfoFree(struct cifs_tcon *tcon, enum smb3_tcon_ref_trace trace)
167 {
168 	if (tcon == NULL) {
169 		cifs_dbg(FYI, "Null buffer passed to tconInfoFree\n");
170 		return;
171 	}
172 	trace_smb3_tcon_ref(tcon->debug_id, tcon->tc_count, trace);
173 	free_cached_dirs(tcon->cfids);
174 	atomic_dec(&tconInfoAllocCount);
175 	kfree(tcon->nativeFileSystem);
176 	kfree_sensitive(tcon->password);
177 	kfree(tcon->origin_fullpath);
178 	kfree(tcon);
179 }
180 
181 void *
182 cifs_buf_get(void)
183 {
184 	void *ret_buf = NULL;
185 	/*
186 	 * SMB2 header is bigger than CIFS one - no problems to clean some
187 	 * more bytes for CIFS.
188 	 */
189 	size_t buf_size = sizeof(struct smb2_hdr);
190 
191 	/*
192 	 * We could use negotiated size instead of max_msgsize -
193 	 * but it may be more efficient to always alloc same size
194 	 * albeit slightly larger than necessary and maxbuffersize
195 	 * defaults to this and can not be bigger.
196 	 */
197 	ret_buf = mempool_alloc(cifs_req_poolp, GFP_NOFS);
198 
199 	/* clear the first few header bytes */
200 	/* for most paths, more is cleared in header_assemble */
201 	memset(ret_buf, 0, buf_size + 3);
202 	atomic_inc(&buf_alloc_count);
203 #ifdef CONFIG_CIFS_STATS2
204 	atomic_inc(&total_buf_alloc_count);
205 #endif /* CONFIG_CIFS_STATS2 */
206 
207 	return ret_buf;
208 }
209 
210 void
211 cifs_buf_release(void *buf_to_free)
212 {
213 	if (buf_to_free == NULL) {
214 		/* cifs_dbg(FYI, "Null buffer passed to cifs_buf_release\n");*/
215 		return;
216 	}
217 	mempool_free(buf_to_free, cifs_req_poolp);
218 
219 	atomic_dec(&buf_alloc_count);
220 	return;
221 }
222 
223 void *
224 cifs_small_buf_get(void)
225 {
226 	void *ret_buf = NULL;
227 
228 /* We could use negotiated size instead of max_msgsize -
229    but it may be more efficient to always alloc same size
230    albeit slightly larger than necessary and maxbuffersize
231    defaults to this and can not be bigger */
232 	ret_buf = mempool_alloc(cifs_sm_req_poolp, GFP_NOFS);
233 	/* No need to clear memory here, cleared in header assemble */
234 	atomic_inc(&small_buf_alloc_count);
235 #ifdef CONFIG_CIFS_STATS2
236 	atomic_inc(&total_small_buf_alloc_count);
237 #endif /* CONFIG_CIFS_STATS2 */
238 
239 	return ret_buf;
240 }
241 
242 void
243 cifs_small_buf_release(void *buf_to_free)
244 {
245 
246 	if (buf_to_free == NULL) {
247 		cifs_dbg(FYI, "Null buffer passed to cifs_small_buf_release\n");
248 		return;
249 	}
250 	mempool_free(buf_to_free, cifs_sm_req_poolp);
251 
252 	atomic_dec(&small_buf_alloc_count);
253 	return;
254 }
255 
256 void
257 free_rsp_buf(int resp_buftype, void *rsp)
258 {
259 	if (resp_buftype == CIFS_SMALL_BUFFER)
260 		cifs_small_buf_release(rsp);
261 	else if (resp_buftype == CIFS_LARGE_BUFFER)
262 		cifs_buf_release(rsp);
263 }
264 
265 void
266 dump_smb(void *buf, int smb_buf_length)
267 {
268 	if (traceSMB == 0)
269 		return;
270 
271 	print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_NONE, 8, 2, buf,
272 		       smb_buf_length, true);
273 }
274 
275 void
276 cifs_autodisable_serverino(struct cifs_sb_info *cifs_sb)
277 {
278 	if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_SERVER_INUM) {
279 		struct cifs_tcon *tcon = NULL;
280 
281 		if (cifs_sb->master_tlink)
282 			tcon = cifs_sb_master_tcon(cifs_sb);
283 
284 		cifs_sb->mnt_cifs_flags &= ~CIFS_MOUNT_SERVER_INUM;
285 		cifs_sb->mnt_cifs_serverino_autodisabled = true;
286 		cifs_dbg(VFS, "Autodisabling the use of server inode numbers on %s\n",
287 			 tcon ? tcon->tree_name : "new server");
288 		cifs_dbg(VFS, "The server doesn't seem to support them properly or the files might be on different servers (DFS)\n");
289 		cifs_dbg(VFS, "Hardlinks will not be recognized on this mount. Consider mounting with the \"noserverino\" option to silence this message.\n");
290 
291 	}
292 }
293 
294 void cifs_set_oplock_level(struct cifsInodeInfo *cinode, __u32 oplock)
295 {
296 	oplock &= 0xF;
297 
298 	if (oplock == OPLOCK_EXCLUSIVE) {
299 		cinode->oplock = CIFS_CACHE_WRITE_FLG | CIFS_CACHE_READ_FLG;
300 		cifs_dbg(FYI, "Exclusive Oplock granted on inode %p\n",
301 			 &cinode->netfs.inode);
302 	} else if (oplock == OPLOCK_READ) {
303 		cinode->oplock = CIFS_CACHE_READ_FLG;
304 		cifs_dbg(FYI, "Level II Oplock granted on inode %p\n",
305 			 &cinode->netfs.inode);
306 	} else
307 		cinode->oplock = 0;
308 }
309 
310 /*
311  * We wait for oplock breaks to be processed before we attempt to perform
312  * writes.
313  */
314 int cifs_get_writer(struct cifsInodeInfo *cinode)
315 {
316 	int rc;
317 
318 start:
319 	rc = wait_on_bit(&cinode->flags, CIFS_INODE_PENDING_OPLOCK_BREAK,
320 			 TASK_KILLABLE);
321 	if (rc)
322 		return rc;
323 
324 	spin_lock(&cinode->writers_lock);
325 	if (!cinode->writers)
326 		set_bit(CIFS_INODE_PENDING_WRITERS, &cinode->flags);
327 	cinode->writers++;
328 	/* Check to see if we have started servicing an oplock break */
329 	if (test_bit(CIFS_INODE_PENDING_OPLOCK_BREAK, &cinode->flags)) {
330 		cinode->writers--;
331 		if (cinode->writers == 0) {
332 			clear_bit(CIFS_INODE_PENDING_WRITERS, &cinode->flags);
333 			wake_up_bit(&cinode->flags, CIFS_INODE_PENDING_WRITERS);
334 		}
335 		spin_unlock(&cinode->writers_lock);
336 		goto start;
337 	}
338 	spin_unlock(&cinode->writers_lock);
339 	return 0;
340 }
341 
342 void cifs_put_writer(struct cifsInodeInfo *cinode)
343 {
344 	spin_lock(&cinode->writers_lock);
345 	cinode->writers--;
346 	if (cinode->writers == 0) {
347 		clear_bit(CIFS_INODE_PENDING_WRITERS, &cinode->flags);
348 		wake_up_bit(&cinode->flags, CIFS_INODE_PENDING_WRITERS);
349 	}
350 	spin_unlock(&cinode->writers_lock);
351 }
352 
353 /**
354  * cifs_queue_oplock_break - queue the oplock break handler for cfile
355  * @cfile: The file to break the oplock on
356  *
357  * This function is called from the demultiplex thread when it
358  * receives an oplock break for @cfile.
359  *
360  * Assumes the tcon->open_file_lock is held.
361  * Assumes cfile->file_info_lock is NOT held.
362  */
363 void cifs_queue_oplock_break(struct cifsFileInfo *cfile)
364 {
365 	/*
366 	 * Bump the handle refcount now while we hold the
367 	 * open_file_lock to enforce the validity of it for the oplock
368 	 * break handler. The matching put is done at the end of the
369 	 * handler.
370 	 */
371 	cifsFileInfo_get(cfile);
372 
373 	queue_work(cifsoplockd_wq, &cfile->oplock_break);
374 }
375 
376 void cifs_done_oplock_break(struct cifsInodeInfo *cinode)
377 {
378 	clear_bit(CIFS_INODE_PENDING_OPLOCK_BREAK, &cinode->flags);
379 	wake_up_bit(&cinode->flags, CIFS_INODE_PENDING_OPLOCK_BREAK);
380 }
381 
382 bool
383 backup_cred(struct cifs_sb_info *cifs_sb)
384 {
385 	if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_CIFS_BACKUPUID) {
386 		if (uid_eq(cifs_sb->ctx->backupuid, current_fsuid()))
387 			return true;
388 	}
389 	if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_CIFS_BACKUPGID) {
390 		if (in_group_p(cifs_sb->ctx->backupgid))
391 			return true;
392 	}
393 
394 	return false;
395 }
396 
397 void
398 cifs_del_pending_open(struct cifs_pending_open *open)
399 {
400 	spin_lock(&tlink_tcon(open->tlink)->open_file_lock);
401 	list_del(&open->olist);
402 	spin_unlock(&tlink_tcon(open->tlink)->open_file_lock);
403 }
404 
405 void
406 cifs_add_pending_open_locked(struct cifs_fid *fid, struct tcon_link *tlink,
407 			     struct cifs_pending_open *open)
408 {
409 	memcpy(open->lease_key, fid->lease_key, SMB2_LEASE_KEY_SIZE);
410 	open->oplock = CIFS_OPLOCK_NO_CHANGE;
411 	open->tlink = tlink;
412 	fid->pending_open = open;
413 	list_add_tail(&open->olist, &tlink_tcon(tlink)->pending_opens);
414 }
415 
416 void
417 cifs_add_pending_open(struct cifs_fid *fid, struct tcon_link *tlink,
418 		      struct cifs_pending_open *open)
419 {
420 	spin_lock(&tlink_tcon(tlink)->open_file_lock);
421 	cifs_add_pending_open_locked(fid, tlink, open);
422 	spin_unlock(&tlink_tcon(open->tlink)->open_file_lock);
423 }
424 
425 /*
426  * Critical section which runs after acquiring deferred_lock.
427  * As there is no reference count on cifs_deferred_close, pdclose
428  * should not be used outside deferred_lock.
429  */
430 bool
431 cifs_is_deferred_close(struct cifsFileInfo *cfile, struct cifs_deferred_close **pdclose)
432 {
433 	struct cifs_deferred_close *dclose;
434 
435 	list_for_each_entry(dclose, &CIFS_I(d_inode(cfile->dentry))->deferred_closes, dlist) {
436 		if ((dclose->netfid == cfile->fid.netfid) &&
437 			(dclose->persistent_fid == cfile->fid.persistent_fid) &&
438 			(dclose->volatile_fid == cfile->fid.volatile_fid)) {
439 			*pdclose = dclose;
440 			return true;
441 		}
442 	}
443 	return false;
444 }
445 
446 /*
447  * Critical section which runs after acquiring deferred_lock.
448  */
449 void
450 cifs_add_deferred_close(struct cifsFileInfo *cfile, struct cifs_deferred_close *dclose)
451 {
452 	bool is_deferred = false;
453 	struct cifs_deferred_close *pdclose;
454 
455 	is_deferred = cifs_is_deferred_close(cfile, &pdclose);
456 	if (is_deferred) {
457 		kfree(dclose);
458 		return;
459 	}
460 
461 	dclose->tlink = cfile->tlink;
462 	dclose->netfid = cfile->fid.netfid;
463 	dclose->persistent_fid = cfile->fid.persistent_fid;
464 	dclose->volatile_fid = cfile->fid.volatile_fid;
465 	list_add_tail(&dclose->dlist, &CIFS_I(d_inode(cfile->dentry))->deferred_closes);
466 }
467 
468 /*
469  * Critical section which runs after acquiring deferred_lock.
470  */
471 void
472 cifs_del_deferred_close(struct cifsFileInfo *cfile)
473 {
474 	bool is_deferred = false;
475 	struct cifs_deferred_close *dclose;
476 
477 	is_deferred = cifs_is_deferred_close(cfile, &dclose);
478 	if (!is_deferred)
479 		return;
480 	list_del(&dclose->dlist);
481 	kfree(dclose);
482 }
483 
484 void
485 cifs_close_deferred_file(struct cifsInodeInfo *cifs_inode)
486 {
487 	struct cifsFileInfo *cfile = NULL;
488 	struct file_list *tmp_list, *tmp_next_list;
489 	LIST_HEAD(file_head);
490 
491 	if (cifs_inode == NULL)
492 		return;
493 
494 	spin_lock(&cifs_inode->open_file_lock);
495 	list_for_each_entry(cfile, &cifs_inode->openFileList, flist) {
496 		if (delayed_work_pending(&cfile->deferred)) {
497 			if (cancel_delayed_work(&cfile->deferred)) {
498 				spin_lock(&cifs_inode->deferred_lock);
499 				cifs_del_deferred_close(cfile);
500 				spin_unlock(&cifs_inode->deferred_lock);
501 
502 				tmp_list = kmalloc_obj(struct file_list,
503 						       GFP_ATOMIC);
504 				if (tmp_list == NULL)
505 					break;
506 				tmp_list->cfile = cfile;
507 				list_add_tail(&tmp_list->list, &file_head);
508 			}
509 		}
510 	}
511 	spin_unlock(&cifs_inode->open_file_lock);
512 
513 	list_for_each_entry_safe(tmp_list, tmp_next_list, &file_head, list) {
514 		_cifsFileInfo_put(tmp_list->cfile, false, false);
515 		list_del(&tmp_list->list);
516 		kfree(tmp_list);
517 	}
518 }
519 
520 void
521 cifs_close_all_deferred_files(struct cifs_tcon *tcon)
522 {
523 	struct cifsFileInfo *cfile;
524 	struct file_list *tmp_list, *tmp_next_list;
525 	LIST_HEAD(file_head);
526 
527 	spin_lock(&tcon->open_file_lock);
528 	list_for_each_entry(cfile, &tcon->openFileList, tlist) {
529 		if (delayed_work_pending(&cfile->deferred)) {
530 			if (cancel_delayed_work(&cfile->deferred)) {
531 				spin_lock(&CIFS_I(d_inode(cfile->dentry))->deferred_lock);
532 				cifs_del_deferred_close(cfile);
533 				spin_unlock(&CIFS_I(d_inode(cfile->dentry))->deferred_lock);
534 
535 				tmp_list = kmalloc_obj(struct file_list,
536 						       GFP_ATOMIC);
537 				if (tmp_list == NULL)
538 					break;
539 				tmp_list->cfile = cfile;
540 				list_add_tail(&tmp_list->list, &file_head);
541 			}
542 		}
543 	}
544 	spin_unlock(&tcon->open_file_lock);
545 
546 	list_for_each_entry_safe(tmp_list, tmp_next_list, &file_head, list) {
547 		_cifsFileInfo_put(tmp_list->cfile, true, false);
548 		list_del(&tmp_list->list);
549 		kfree(tmp_list);
550 	}
551 }
552 
553 void cifs_close_deferred_file_under_dentry(struct cifs_tcon *tcon,
554 					   struct dentry *dentry)
555 {
556 	struct file_list *tmp_list, *tmp_next_list;
557 	struct cifsFileInfo *cfile;
558 	LIST_HEAD(file_head);
559 
560 	spin_lock(&tcon->open_file_lock);
561 	list_for_each_entry(cfile, &tcon->openFileList, tlist) {
562 		if ((cfile->dentry == dentry) &&
563 		    delayed_work_pending(&cfile->deferred) &&
564 		    cancel_delayed_work(&cfile->deferred)) {
565 			spin_lock(&CIFS_I(d_inode(cfile->dentry))->deferred_lock);
566 			cifs_del_deferred_close(cfile);
567 			spin_unlock(&CIFS_I(d_inode(cfile->dentry))->deferred_lock);
568 
569 			tmp_list = kmalloc_obj(struct file_list, GFP_ATOMIC);
570 			if (tmp_list == NULL)
571 				break;
572 			tmp_list->cfile = cfile;
573 			list_add_tail(&tmp_list->list, &file_head);
574 		}
575 	}
576 	spin_unlock(&tcon->open_file_lock);
577 
578 	list_for_each_entry_safe(tmp_list, tmp_next_list, &file_head, list) {
579 		_cifsFileInfo_put(tmp_list->cfile, true, false);
580 		list_del(&tmp_list->list);
581 		kfree(tmp_list);
582 	}
583 }
584 
585 /*
586  * If a dentry has been deleted, all corresponding open handles should know that
587  * so that we do not defer close them.
588  */
589 void cifs_mark_open_handles_for_deleted_file(struct inode *inode,
590 					     const char *path)
591 {
592 	struct cifsFileInfo *cfile;
593 	void *page;
594 	const char *full_path;
595 	struct cifsInodeInfo *cinode = CIFS_I(inode);
596 
597 	page = alloc_dentry_path();
598 	spin_lock(&cinode->open_file_lock);
599 
600 	/*
601 	 * note: we need to construct path from dentry and compare only if the
602 	 * inode has any hardlinks. When number of hardlinks is 1, we can just
603 	 * mark all open handles since they are going to be from the same file.
604 	 */
605 	if (inode->i_nlink > 1) {
606 		list_for_each_entry(cfile, &cinode->openFileList, flist) {
607 			full_path = build_path_from_dentry(cfile->dentry, page);
608 			if (!IS_ERR(full_path) && strcmp(full_path, path) == 0)
609 				cfile->status_file_deleted = true;
610 		}
611 	} else {
612 		list_for_each_entry(cfile, &cinode->openFileList, flist)
613 			cfile->status_file_deleted = true;
614 	}
615 	spin_unlock(&cinode->open_file_lock);
616 	free_dentry_path(page);
617 }
618 
619 /* parses DFS referral V3 structure
620  * caller is responsible for freeing target_nodes
621  * returns:
622  * - on success - 0
623  * - on failure - errno
624  */
625 int
626 parse_dfs_referrals(struct get_dfs_referral_rsp *rsp, u32 rsp_size,
627 		    unsigned int *num_of_nodes,
628 		    struct dfs_info3_param **target_nodes,
629 		    const struct nls_table *nls_codepage, int remap,
630 		    const char *searchName, bool is_unicode)
631 {
632 	int i, rc = 0;
633 	char *data_end;
634 	struct dfs_referral_level_3 *ref;
635 
636 	if (rsp_size < sizeof(*rsp)) {
637 		cifs_dbg(VFS | ONCE,
638 			 "%s: header is malformed (size is %u, must be %zu)\n",
639 			 __func__, rsp_size, sizeof(*rsp));
640 		rc = -EINVAL;
641 		goto parse_DFS_referrals_exit;
642 	}
643 
644 	*num_of_nodes = le16_to_cpu(rsp->NumberOfReferrals);
645 
646 	if (*num_of_nodes < 1) {
647 		cifs_dbg(VFS | ONCE, "%s: [path=%s] num_referrals must be at least > 0, but we got %d\n",
648 			 __func__, searchName, *num_of_nodes);
649 		rc = -ENOENT;
650 		goto parse_DFS_referrals_exit;
651 	}
652 
653 	if (sizeof(*rsp) + *num_of_nodes * sizeof(REFERRAL3) > rsp_size) {
654 		cifs_dbg(VFS | ONCE,
655 			 "%s: malformed buffer (size is %u, must be at least %zu)\n",
656 			 __func__, rsp_size,
657 			 sizeof(*rsp) + *num_of_nodes * sizeof(REFERRAL3));
658 		rc = -EINVAL;
659 		goto parse_DFS_referrals_exit;
660 	}
661 
662 	ref = (struct dfs_referral_level_3 *) &(rsp->referrals);
663 	if (ref->VersionNumber != cpu_to_le16(3)) {
664 		cifs_dbg(VFS, "Referrals of V%d version are not supported, should be V3\n",
665 			 le16_to_cpu(ref->VersionNumber));
666 		rc = -EINVAL;
667 		goto parse_DFS_referrals_exit;
668 	}
669 
670 	/* get the upper boundary of the resp buffer */
671 	data_end = (char *)rsp + rsp_size;
672 
673 	cifs_dbg(FYI, "num_referrals: %d dfs flags: 0x%x ...\n",
674 		 *num_of_nodes, le32_to_cpu(rsp->DFSFlags));
675 
676 	*target_nodes = kzalloc_objs(struct dfs_info3_param, *num_of_nodes,
677 				     GFP_KERNEL);
678 	if (*target_nodes == NULL) {
679 		rc = -ENOMEM;
680 		goto parse_DFS_referrals_exit;
681 	}
682 
683 	/* collect necessary data from referrals */
684 	for (i = 0; i < *num_of_nodes; i++) {
685 		char *temp;
686 		int max_len;
687 		struct dfs_info3_param *node = (*target_nodes)+i;
688 
689 		node->flags = le32_to_cpu(rsp->DFSFlags);
690 		if (is_unicode) {
691 			__le16 *tmp = kmalloc(strlen(searchName)*2 + 2,
692 						GFP_KERNEL);
693 			if (tmp == NULL) {
694 				rc = -ENOMEM;
695 				goto parse_DFS_referrals_exit;
696 			}
697 			cifsConvertToUTF16((__le16 *) tmp, searchName,
698 					   PATH_MAX, nls_codepage, remap);
699 			node->path_consumed = cifs_utf16_bytes(tmp,
700 					le16_to_cpu(rsp->PathConsumed),
701 					nls_codepage);
702 			kfree(tmp);
703 		} else
704 			node->path_consumed = le16_to_cpu(rsp->PathConsumed);
705 
706 		node->server_type = le16_to_cpu(ref->ServerType);
707 		node->ref_flag = le16_to_cpu(ref->ReferralEntryFlags);
708 
709 		/* copy DfsPath */
710 		temp = (char *)ref + le16_to_cpu(ref->DfsPathOffset);
711 		max_len = data_end - temp;
712 		node->path_name = cifs_strndup_from_utf16(temp, max_len,
713 						is_unicode, nls_codepage);
714 		if (!node->path_name) {
715 			rc = -ENOMEM;
716 			goto parse_DFS_referrals_exit;
717 		}
718 
719 		/* copy link target UNC */
720 		temp = (char *)ref + le16_to_cpu(ref->NetworkAddressOffset);
721 		max_len = data_end - temp;
722 		node->node_name = cifs_strndup_from_utf16(temp, max_len,
723 						is_unicode, nls_codepage);
724 		if (!node->node_name) {
725 			rc = -ENOMEM;
726 			goto parse_DFS_referrals_exit;
727 		}
728 
729 		node->ttl = le32_to_cpu(ref->TimeToLive);
730 
731 		ref++;
732 	}
733 
734 parse_DFS_referrals_exit:
735 	if (rc) {
736 		free_dfs_info_array(*target_nodes, *num_of_nodes);
737 		*target_nodes = NULL;
738 		*num_of_nodes = 0;
739 	}
740 	return rc;
741 }
742 
743 /**
744  * cifs_alloc_hash - allocate hash and hash context together
745  * @name: The name of the crypto hash algo
746  * @sdesc: SHASH descriptor where to put the pointer to the hash TFM
747  *
748  * The caller has to make sure @sdesc is initialized to either NULL or
749  * a valid context. It can be freed via cifs_free_hash().
750  */
751 int
752 cifs_alloc_hash(const char *name, struct shash_desc **sdesc)
753 {
754 	int rc = 0;
755 	struct crypto_shash *alg = NULL;
756 
757 	if (*sdesc)
758 		return 0;
759 
760 	alg = crypto_alloc_shash(name, 0, 0);
761 	if (IS_ERR(alg)) {
762 		cifs_dbg(VFS, "Could not allocate shash TFM '%s'\n", name);
763 		rc = PTR_ERR(alg);
764 		*sdesc = NULL;
765 		return rc;
766 	}
767 
768 	*sdesc = kmalloc(sizeof(struct shash_desc) + crypto_shash_descsize(alg), GFP_KERNEL);
769 	if (*sdesc == NULL) {
770 		cifs_dbg(VFS, "no memory left to allocate shash TFM '%s'\n", name);
771 		crypto_free_shash(alg);
772 		return -ENOMEM;
773 	}
774 
775 	(*sdesc)->tfm = alg;
776 	return 0;
777 }
778 
779 /**
780  * cifs_free_hash - free hash and hash context together
781  * @sdesc: Where to find the pointer to the hash TFM
782  *
783  * Freeing a NULL descriptor is safe.
784  */
785 void
786 cifs_free_hash(struct shash_desc **sdesc)
787 {
788 	if (unlikely(!sdesc) || !*sdesc)
789 		return;
790 
791 	if ((*sdesc)->tfm) {
792 		crypto_free_shash((*sdesc)->tfm);
793 		(*sdesc)->tfm = NULL;
794 	}
795 
796 	kfree_sensitive(*sdesc);
797 	*sdesc = NULL;
798 }
799 
800 void extract_unc_hostname(const char *unc, const char **h, size_t *len)
801 {
802 	const char *end;
803 
804 	/* skip initial slashes */
805 	while (*unc && (*unc == '\\' || *unc == '/'))
806 		unc++;
807 
808 	end = unc;
809 
810 	while (*end && !(*end == '\\' || *end == '/'))
811 		end++;
812 
813 	*h = unc;
814 	*len = end - unc;
815 }
816 
817 /**
818  * copy_path_name - copy src path to dst, possibly truncating
819  * @dst: The destination buffer
820  * @src: The source name
821  *
822  * returns number of bytes written (including trailing nul)
823  */
824 int copy_path_name(char *dst, const char *src)
825 {
826 	int name_len;
827 
828 	/*
829 	 * PATH_MAX includes nul, so if strlen(src) >= PATH_MAX it
830 	 * will truncate and strlen(dst) will be PATH_MAX-1
831 	 */
832 	name_len = strscpy(dst, src, PATH_MAX);
833 	if (WARN_ON_ONCE(name_len < 0))
834 		name_len = PATH_MAX-1;
835 
836 	/* we count the trailing nul */
837 	name_len++;
838 	return name_len;
839 }
840 
841 struct super_cb_data {
842 	void *data;
843 	struct super_block *sb;
844 };
845 
846 static void tcon_super_cb(struct super_block *sb, void *arg)
847 {
848 	struct super_cb_data *sd = arg;
849 	struct cifs_sb_info *cifs_sb;
850 	struct cifs_tcon *t1 = sd->data, *t2;
851 
852 	if (sd->sb)
853 		return;
854 
855 	cifs_sb = CIFS_SB(sb);
856 	t2 = cifs_sb_master_tcon(cifs_sb);
857 
858 	spin_lock(&t2->tc_lock);
859 	if ((t1->ses == t2->ses ||
860 	     t1->ses->dfs_root_ses == t2->ses->dfs_root_ses) &&
861 	    t1->ses->server == t2->ses->server &&
862 	    t2->origin_fullpath &&
863 	    dfs_src_pathname_equal(t2->origin_fullpath, t1->origin_fullpath))
864 		sd->sb = sb;
865 	spin_unlock(&t2->tc_lock);
866 }
867 
868 static struct super_block *__cifs_get_super(void (*f)(struct super_block *, void *),
869 					    void *data)
870 {
871 	struct super_cb_data sd = {
872 		.data = data,
873 		.sb = NULL,
874 	};
875 	struct file_system_type **fs_type = (struct file_system_type *[]) {
876 		&cifs_fs_type, &smb3_fs_type, NULL,
877 	};
878 
879 	for (; *fs_type; fs_type++) {
880 		iterate_supers_type(*fs_type, f, &sd);
881 		if (sd.sb) {
882 			/*
883 			 * Grab an active reference in order to prevent automounts (DFS links)
884 			 * of expiring and then freeing up our cifs superblock pointer while
885 			 * we're doing failover.
886 			 */
887 			cifs_sb_active(sd.sb);
888 			return sd.sb;
889 		}
890 	}
891 	pr_warn_once("%s: could not find dfs superblock\n", __func__);
892 	return ERR_PTR(-EINVAL);
893 }
894 
895 static void __cifs_put_super(struct super_block *sb)
896 {
897 	if (!IS_ERR_OR_NULL(sb))
898 		cifs_sb_deactive(sb);
899 }
900 
901 struct super_block *cifs_get_dfs_tcon_super(struct cifs_tcon *tcon)
902 {
903 	spin_lock(&tcon->tc_lock);
904 	if (!tcon->origin_fullpath) {
905 		spin_unlock(&tcon->tc_lock);
906 		return ERR_PTR(-ENOENT);
907 	}
908 	spin_unlock(&tcon->tc_lock);
909 	return __cifs_get_super(tcon_super_cb, tcon);
910 }
911 
912 void cifs_put_tcp_super(struct super_block *sb)
913 {
914 	__cifs_put_super(sb);
915 }
916 
917 #ifdef CONFIG_CIFS_DFS_UPCALL
918 int match_target_ip(struct TCP_Server_Info *server,
919 		    const char *host, size_t hostlen,
920 		    bool *result)
921 {
922 	struct sockaddr_storage ss;
923 	int rc;
924 
925 	cifs_dbg(FYI, "%s: hostname=%.*s\n", __func__, (int)hostlen, host);
926 
927 	*result = false;
928 
929 	rc = dns_resolve_name(server->dns_dom, host, hostlen,
930 			      (struct sockaddr *)&ss);
931 	if (rc < 0)
932 		return rc;
933 
934 	spin_lock(&server->srv_lock);
935 	*result = cifs_match_ipaddr((struct sockaddr *)&server->dstaddr, (struct sockaddr *)&ss);
936 	spin_unlock(&server->srv_lock);
937 	cifs_dbg(FYI, "%s: ip addresses matched: %s\n", __func__, str_yes_no(*result));
938 	return 0;
939 }
940 
941 int cifs_update_super_prepath(struct cifs_sb_info *cifs_sb, char *prefix)
942 {
943 	int rc;
944 
945 	kfree(cifs_sb->prepath);
946 	cifs_sb->prepath = NULL;
947 
948 	if (prefix && *prefix) {
949 		cifs_sb->prepath = cifs_sanitize_prepath(prefix, GFP_ATOMIC);
950 		if (IS_ERR(cifs_sb->prepath)) {
951 			rc = PTR_ERR(cifs_sb->prepath);
952 			cifs_sb->prepath = NULL;
953 			return rc;
954 		}
955 		if (cifs_sb->prepath)
956 			convert_delimiter(cifs_sb->prepath, CIFS_DIR_SEP(cifs_sb));
957 	}
958 
959 	cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
960 	return 0;
961 }
962 
963 /*
964  * Handle weird Windows SMB server behaviour. It responds with
965  * STATUS_OBJECT_NAME_INVALID code to SMB2 QUERY_INFO request for
966  * "\<server>\<dfsname>\<linkpath>" DFS reference, where <dfsname> contains
967  * non-ASCII unicode symbols.
968  */
969 int cifs_inval_name_dfs_link_error(const unsigned int xid,
970 				   struct cifs_tcon *tcon,
971 				   struct cifs_sb_info *cifs_sb,
972 				   const char *full_path,
973 				   bool *islink)
974 {
975 	struct TCP_Server_Info *server = tcon->ses->server;
976 	struct cifs_ses *ses = tcon->ses;
977 	size_t len;
978 	char *path;
979 	char *ref_path;
980 
981 	*islink = false;
982 
983 	/*
984 	 * Fast path - skip check when @full_path doesn't have a prefix path to
985 	 * look up or tcon is not DFS.
986 	 */
987 	if (strlen(full_path) < 2 || !cifs_sb ||
988 	    (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_DFS) ||
989 	    !is_tcon_dfs(tcon))
990 		return 0;
991 
992 	spin_lock(&server->srv_lock);
993 	if (!server->leaf_fullpath) {
994 		spin_unlock(&server->srv_lock);
995 		return 0;
996 	}
997 	spin_unlock(&server->srv_lock);
998 
999 	/*
1000 	 * Slow path - tcon is DFS and @full_path has prefix path, so attempt
1001 	 * to get a referral to figure out whether it is an DFS link.
1002 	 */
1003 	len = strnlen(tcon->tree_name, MAX_TREE_SIZE + 1) + strlen(full_path) + 1;
1004 	path = kmalloc(len, GFP_KERNEL);
1005 	if (!path)
1006 		return -ENOMEM;
1007 
1008 	scnprintf(path, len, "%s%s", tcon->tree_name, full_path);
1009 	ref_path = dfs_cache_canonical_path(path + 1, cifs_sb->local_nls,
1010 					    cifs_remap(cifs_sb));
1011 	kfree(path);
1012 
1013 	if (IS_ERR(ref_path)) {
1014 		if (PTR_ERR(ref_path) != -EINVAL)
1015 			return PTR_ERR(ref_path);
1016 	} else {
1017 		struct dfs_info3_param *refs = NULL;
1018 		int num_refs = 0;
1019 
1020 		/*
1021 		 * XXX: we are not using dfs_cache_find() here because we might
1022 		 * end up filling all the DFS cache and thus potentially
1023 		 * removing cached DFS targets that the client would eventually
1024 		 * need during failover.
1025 		 */
1026 		ses = CIFS_DFS_ROOT_SES(ses);
1027 		if (ses->server->ops->get_dfs_refer &&
1028 		    !ses->server->ops->get_dfs_refer(xid, ses, ref_path, &refs,
1029 						     &num_refs, cifs_sb->local_nls,
1030 						     cifs_remap(cifs_sb)))
1031 			*islink = refs[0].server_type == DFS_TYPE_LINK;
1032 		free_dfs_info_array(refs, num_refs);
1033 		kfree(ref_path);
1034 	}
1035 	return 0;
1036 }
1037 #endif
1038 
1039 int cifs_wait_for_server_reconnect(struct TCP_Server_Info *server, bool retry)
1040 {
1041 	int timeout = 10;
1042 	int rc;
1043 
1044 	spin_lock(&server->srv_lock);
1045 	if (server->tcpStatus != CifsNeedReconnect) {
1046 		spin_unlock(&server->srv_lock);
1047 		return 0;
1048 	}
1049 	timeout *= server->nr_targets;
1050 	spin_unlock(&server->srv_lock);
1051 
1052 	/*
1053 	 * Give demultiplex thread up to 10 seconds to each target available for
1054 	 * reconnect -- should be greater than cifs socket timeout which is 7
1055 	 * seconds.
1056 	 *
1057 	 * On "soft" mounts we wait once. Hard mounts keep retrying until
1058 	 * process is killed or server comes back on-line.
1059 	 */
1060 	do {
1061 		rc = wait_event_interruptible_timeout(server->response_q,
1062 						      (server->tcpStatus != CifsNeedReconnect),
1063 						      timeout * HZ);
1064 		if (rc < 0) {
1065 			cifs_dbg(FYI, "%s: aborting reconnect due to received signal\n",
1066 				 __func__);
1067 			return -ERESTARTSYS;
1068 		}
1069 
1070 		/* are we still trying to reconnect? */
1071 		spin_lock(&server->srv_lock);
1072 		if (server->tcpStatus != CifsNeedReconnect) {
1073 			spin_unlock(&server->srv_lock);
1074 			return 0;
1075 		}
1076 		spin_unlock(&server->srv_lock);
1077 	} while (retry);
1078 
1079 	cifs_dbg(FYI, "%s: gave up waiting on reconnect\n", __func__);
1080 	return -EHOSTDOWN;
1081 }
1082