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