xref: /linux/fs/smb/client/file.c (revision b2c49578d3423c81eb1e6ac4c506d57ea4c3a87c)
1 // SPDX-License-Identifier: LGPL-2.1
2 /*
3  *
4  *   vfs operations that deal with files
5  *
6  *   Copyright (C) International Business Machines  Corp., 2002,2010
7  *   Author(s): Steve French (sfrench@us.ibm.com)
8  *              Jeremy Allison (jra@samba.org)
9  *
10  */
11 #include <linux/fs.h>
12 #include <linux/fs_struct.h>
13 #include <linux/filelock.h>
14 #include <linux/backing-dev.h>
15 #include <linux/stat.h>
16 #include <linux/fcntl.h>
17 #include <linux/pagemap.h>
18 #include <linux/writeback.h>
19 #include <linux/task_io_accounting_ops.h>
20 #include <linux/delay.h>
21 #include <linux/mount.h>
22 #include <linux/slab.h>
23 #include <linux/swap_ops.h>
24 #include <linux/mm.h>
25 #include <asm/div64.h>
26 #include "cifsfs.h"
27 #include "cifsglob.h"
28 #include "cifsproto.h"
29 #include "smb2proto.h"
30 #include "cifs_unicode.h"
31 #include "cifs_debug.h"
32 #include "cifs_fs_sb.h"
33 #include "fscache.h"
34 #include "smbdirect.h"
35 #include "fs_context.h"
36 #include "cifs_ioctl.h"
37 #include "cached_dir.h"
38 #include <trace/events/netfs.h>
39 
40 static int cifs_reopen_file(struct cifsFileInfo *cfile, bool can_flush);
41 
42 /*
43  * Prepare a subrequest to upload to the server.  We need to allocate credits
44  * so that we know the maximum amount of data that we can include in it.
45  */
46 static void cifs_prepare_write(struct netfs_io_subrequest *subreq)
47 {
48 	struct cifs_io_subrequest *wdata =
49 		container_of(subreq, struct cifs_io_subrequest, subreq);
50 	struct cifs_io_request *req = wdata->req;
51 	struct netfs_io_stream *stream = &req->rreq.io_streams[subreq->stream_nr];
52 	struct TCP_Server_Info *server;
53 	struct cifsFileInfo *open_file = req->cfile;
54 	struct cifs_sb_info *cifs_sb = CIFS_SB(wdata->rreq->inode->i_sb);
55 	size_t wsize = req->rreq.wsize;
56 	int rc;
57 
58 	if (!wdata->have_xid) {
59 		wdata->xid = get_xid();
60 		wdata->have_xid = true;
61 	}
62 
63 	server = cifs_pick_channel(tlink_tcon(open_file->tlink)->ses);
64 	wdata->server = server;
65 
66 	if (cifs_sb->ctx->wsize == 0)
67 		cifs_negotiate_wsize(server, cifs_sb->ctx,
68 				     tlink_tcon(req->cfile->tlink));
69 
70 retry:
71 	if (open_file->invalidHandle) {
72 		rc = cifs_reopen_file(open_file, false);
73 		if (rc < 0) {
74 			if (rc == -EAGAIN)
75 				goto retry;
76 			subreq->error = rc;
77 			return netfs_prepare_write_failed(subreq);
78 		}
79 	}
80 
81 	rc = server->ops->wait_mtu_credits(server, wsize, &stream->sreq_max_len,
82 					   &wdata->credits);
83 	if (rc < 0) {
84 		subreq->error = rc;
85 		return netfs_prepare_write_failed(subreq);
86 	}
87 
88 	wdata->credits.rreq_debug_id = subreq->rreq->debug_id;
89 	wdata->credits.rreq_debug_index = subreq->debug_index;
90 	wdata->credits.in_flight_check = 1;
91 	trace_smb3_rw_credits(wdata->rreq->debug_id,
92 			      wdata->subreq.debug_index,
93 			      wdata->credits.value,
94 			      server->credits, server->in_flight,
95 			      wdata->credits.value,
96 			      cifs_trace_rw_credits_write_prepare);
97 
98 #ifdef CONFIG_CIFS_SMB_DIRECT
99 	if (server->smbd_conn) {
100 		const struct smbdirect_socket_parameters *sp =
101 			smbd_get_parameters(server->smbd_conn);
102 
103 		stream->sreq_max_segs = sp->max_frmr_depth;
104 	}
105 #endif
106 }
107 
108 /*
109  * Issue a subrequest to upload to the server.
110  */
111 static void cifs_issue_write(struct netfs_io_subrequest *subreq)
112 {
113 	struct cifs_io_subrequest *wdata =
114 		container_of(subreq, struct cifs_io_subrequest, subreq);
115 	struct cifs_sb_info *sbi = CIFS_SB(subreq->rreq->inode->i_sb);
116 	int rc;
117 
118 	if (cifs_forced_shutdown(sbi)) {
119 		rc = smb_EIO(smb_eio_trace_forced_shutdown);
120 		goto fail;
121 	}
122 
123 	rc = adjust_credits(wdata->server, wdata, cifs_trace_rw_credits_issue_write_adjust);
124 	if (rc)
125 		goto fail;
126 
127 	rc = -EAGAIN;
128 	if (wdata->req->cfile->invalidHandle)
129 		goto fail;
130 
131 	wdata->server->ops->async_writev(wdata);
132 out:
133 	return;
134 
135 fail:
136 	if (rc == -EAGAIN)
137 		trace_netfs_sreq(subreq, netfs_sreq_trace_retry);
138 	else
139 		trace_netfs_sreq(subreq, netfs_sreq_trace_fail);
140 	add_credits_and_wake_if(wdata->server, &wdata->credits, 0);
141 	cifs_write_subrequest_terminated(wdata, rc);
142 	goto out;
143 }
144 
145 static void cifs_netfs_invalidate_cache(struct netfs_io_request *wreq)
146 {
147 	cifs_invalidate_cache(wreq->inode, 0);
148 }
149 
150 /*
151  * Negotiate the size of a read operation on behalf of the netfs library.
152  */
153 static int cifs_prepare_read(struct netfs_io_subrequest *subreq)
154 {
155 	struct netfs_io_request *rreq = subreq->rreq;
156 	struct cifs_io_subrequest *rdata = container_of(subreq, struct cifs_io_subrequest, subreq);
157 	struct cifs_io_request *req = container_of(subreq->rreq, struct cifs_io_request, rreq);
158 	struct TCP_Server_Info *server;
159 	struct cifs_sb_info *cifs_sb = CIFS_SB(rreq->inode->i_sb);
160 	size_t size;
161 	int rc = 0;
162 
163 	if (!rdata->have_xid) {
164 		rdata->xid = get_xid();
165 		rdata->have_xid = true;
166 	}
167 
168 	server = cifs_pick_channel(tlink_tcon(req->cfile->tlink)->ses);
169 	rdata->server = server;
170 
171 	if (cifs_sb->ctx->rsize == 0)
172 		cifs_negotiate_rsize(server, cifs_sb->ctx,
173 				     tlink_tcon(req->cfile->tlink));
174 
175 	rc = server->ops->wait_mtu_credits(server, cifs_sb->ctx->rsize,
176 					   &size, &rdata->credits);
177 	if (rc)
178 		return rc;
179 
180 	rreq->io_streams[0].sreq_max_len = size;
181 
182 	rdata->credits.in_flight_check = 1;
183 	rdata->credits.rreq_debug_id = rreq->debug_id;
184 	rdata->credits.rreq_debug_index = subreq->debug_index;
185 
186 	trace_smb3_rw_credits(rdata->rreq->debug_id,
187 			      rdata->subreq.debug_index,
188 			      rdata->credits.value,
189 			      server->credits, server->in_flight, 0,
190 			      cifs_trace_rw_credits_read_submit);
191 
192 #ifdef CONFIG_CIFS_SMB_DIRECT
193 	if (server->smbd_conn) {
194 		const struct smbdirect_socket_parameters *sp =
195 			smbd_get_parameters(server->smbd_conn);
196 
197 		rreq->io_streams[0].sreq_max_segs = sp->max_frmr_depth;
198 	}
199 #endif
200 	return 0;
201 }
202 
203 /*
204  * Issue a read operation on behalf of the netfs helper functions.  We're asked
205  * to make a read of a certain size at a point in the file.  We are permitted
206  * to only read a portion of that, but as long as we read something, the netfs
207  * helper will call us again so that we can issue another read.
208  */
209 static void cifs_issue_read(struct netfs_io_subrequest *subreq)
210 {
211 	struct netfs_io_request *rreq = subreq->rreq;
212 	struct cifs_io_subrequest *rdata = container_of(subreq, struct cifs_io_subrequest, subreq);
213 	struct cifs_io_request *req = container_of(subreq->rreq, struct cifs_io_request, rreq);
214 	struct TCP_Server_Info *server = rdata->server;
215 	int rc = 0;
216 
217 	cifs_dbg(FYI, "%s: op=%08x[%x] mapping=%p len=%zu/%zu\n",
218 		 __func__, rreq->debug_id, subreq->debug_index, rreq->mapping,
219 		 subreq->transferred, subreq->len);
220 
221 	rc = adjust_credits(server, rdata, cifs_trace_rw_credits_issue_read_adjust);
222 	if (rc)
223 		goto failed;
224 
225 	if (req->cfile->invalidHandle) {
226 		do {
227 			rc = cifs_reopen_file(req->cfile, true);
228 		} while (rc == -EAGAIN);
229 		if (rc)
230 			goto failed;
231 	}
232 
233 	if (subreq->rreq->origin != NETFS_UNBUFFERED_READ &&
234 	    subreq->rreq->origin != NETFS_DIO_READ)
235 		__set_bit(NETFS_SREQ_CLEAR_TAIL, &subreq->flags);
236 
237 	trace_netfs_sreq(subreq, netfs_sreq_trace_submit);
238 	rc = rdata->server->ops->async_readv(rdata);
239 	if (rc)
240 		goto failed;
241 	return;
242 
243 failed:
244 	add_credits_and_wake_if(rdata->server, &rdata->credits, 0);
245 	subreq->error = rc;
246 	netfs_read_subreq_terminated(subreq);
247 }
248 
249 /*
250  * Writeback calls this when it finds a folio that needs uploading.  This isn't
251  * called if writeback only has copy-to-cache to deal with.
252  */
253 static void cifs_begin_writeback(struct netfs_io_request *wreq)
254 {
255 	struct cifs_io_request *req = container_of(wreq, struct cifs_io_request, rreq);
256 	int ret;
257 
258 	ret = cifs_get_writable_file(CIFS_I(wreq->inode), FIND_ANY, &req->cfile);
259 	if (ret) {
260 		cifs_dbg(VFS, "No writable handle in writepages ret=%d\n", ret);
261 		return;
262 	}
263 
264 	wreq->io_streams[0].avail = true;
265 }
266 
267 /*
268  * Initialise a request.
269  */
270 static int cifs_init_request(struct netfs_io_request *rreq, struct file *file)
271 {
272 	struct cifs_io_request *req = container_of(rreq, struct cifs_io_request, rreq);
273 	struct cifs_sb_info *cifs_sb = CIFS_SB(rreq->inode);
274 	struct cifsFileInfo *open_file = NULL;
275 
276 	rreq->rsize = cifs_sb->ctx->rsize;
277 	rreq->wsize = cifs_sb->ctx->wsize;
278 	req->pid = current->tgid; // Ummm...  This may be a workqueue
279 
280 	if (file) {
281 		open_file = file->private_data;
282 		rreq->netfs_priv = file->private_data;
283 		req->cfile = cifsFileInfo_get(open_file);
284 		if (cifs_sb_flags(cifs_sb) & CIFS_MOUNT_RWPIDFORWARD)
285 			req->pid = req->cfile->pid;
286 	} else if (rreq->origin != NETFS_WRITEBACK) {
287 		WARN_ON_ONCE(1);
288 		return smb_EIO1(smb_eio_trace_not_netfs_writeback, rreq->origin);
289 	}
290 
291 	atomic_inc(&cifs_sb->outstanding_rreq);
292 	return 0;
293 }
294 
295 /*
296  * Completion of a request operation.
297  */
298 static void cifs_rreq_done(struct netfs_io_request *rreq)
299 {
300 	struct timespec64 atime, mtime;
301 	struct inode *inode = rreq->inode;
302 
303 	/* we do not want atime to be less than mtime, it broke some apps */
304 	atime = inode_set_atime_to_ts(inode, current_time(inode));
305 	mtime = inode_get_mtime(inode);
306 	if (timespec64_compare(&atime, &mtime) < 0)
307 		inode_set_atime_to_ts(inode, inode_get_mtime(inode));
308 }
309 
310 static void cifs_free_request(struct netfs_io_request *rreq)
311 {
312 	struct cifs_io_request *req = container_of(rreq, struct cifs_io_request, rreq);
313 	struct cifs_sb_info *cifs_sb = CIFS_SB(rreq->inode->i_sb);
314 
315 	if (req->cfile)
316 		cifsFileInfo_put(req->cfile);
317 
318 	if (atomic_dec_and_test(&cifs_sb->outstanding_rreq))
319 		wake_up_var(&cifs_sb->outstanding_rreq);
320 }
321 
322 static void cifs_free_subrequest(struct netfs_io_subrequest *subreq)
323 {
324 	struct cifs_io_subrequest *rdata =
325 		container_of(subreq, struct cifs_io_subrequest, subreq);
326 	int rc = subreq->error;
327 
328 	if (rdata->subreq.source == NETFS_DOWNLOAD_FROM_SERVER) {
329 #ifdef CONFIG_CIFS_SMB_DIRECT
330 		if (rdata->mr) {
331 			smbd_deregister_mr(rdata->mr);
332 			rdata->mr = NULL;
333 		}
334 #endif
335 	}
336 
337 	if (rdata->credits.value != 0) {
338 		trace_smb3_rw_credits(rdata->rreq->debug_id,
339 				      rdata->subreq.debug_index,
340 				      rdata->credits.value,
341 				      rdata->server ? rdata->server->credits : 0,
342 				      rdata->server ? rdata->server->in_flight : 0,
343 				      -rdata->credits.value,
344 				      cifs_trace_rw_credits_free_subreq);
345 		if (rdata->server)
346 			add_credits_and_wake_if(rdata->server, &rdata->credits, 0);
347 		else
348 			rdata->credits.value = 0;
349 	}
350 
351 	if (rdata->have_xid)
352 		free_xid(rdata->xid);
353 }
354 
355 const struct netfs_request_ops cifs_req_ops = {
356 	.request_pool		= &cifs_io_request_pool,
357 	.subrequest_pool	= &cifs_io_subrequest_pool,
358 	.init_request		= cifs_init_request,
359 	.free_request		= cifs_free_request,
360 	.free_subrequest	= cifs_free_subrequest,
361 	.prepare_read		= cifs_prepare_read,
362 	.issue_read		= cifs_issue_read,
363 	.done			= cifs_rreq_done,
364 	.begin_writeback	= cifs_begin_writeback,
365 	.prepare_write		= cifs_prepare_write,
366 	.issue_write		= cifs_issue_write,
367 	.invalidate_cache	= cifs_netfs_invalidate_cache,
368 };
369 
370 /*
371  * Mark as invalid, all open files on tree connections since they
372  * were closed when session to server was lost.
373  */
374 void
375 cifs_mark_open_files_invalid(struct cifs_tcon *tcon)
376 {
377 	struct cifsFileInfo *open_file = NULL;
378 	struct list_head *tmp;
379 	struct list_head *tmp1;
380 
381 	/* only send once per connect */
382 	spin_lock(&tcon->tc_lock);
383 	if (tcon->need_reconnect)
384 		tcon->status = TID_NEED_RECON;
385 
386 	if (tcon->status != TID_NEED_RECON) {
387 		spin_unlock(&tcon->tc_lock);
388 		return;
389 	}
390 	tcon->status = TID_IN_FILES_INVALIDATE;
391 	spin_unlock(&tcon->tc_lock);
392 
393 	/* list all files open on tree connection and mark them invalid */
394 	spin_lock(&tcon->open_file_lock);
395 	list_for_each_safe(tmp, tmp1, &tcon->openFileList) {
396 		open_file = list_entry(tmp, struct cifsFileInfo, tlist);
397 		open_file->invalidHandle = true;
398 		open_file->oplock_break_cancelled = true;
399 	}
400 	spin_unlock(&tcon->open_file_lock);
401 
402 	invalidate_all_cached_dirs(tcon, true);
403 	spin_lock(&tcon->tc_lock);
404 	if (tcon->status == TID_IN_FILES_INVALIDATE)
405 		tcon->status = TID_NEED_TCON;
406 	spin_unlock(&tcon->tc_lock);
407 
408 	/*
409 	 * BB Add call to evict_inodes(sb) for all superblocks mounted
410 	 * to this tcon.
411 	 */
412 }
413 
414 static inline int cifs_convert_flags(unsigned int oflags, int rdwr_for_fscache)
415 {
416 	int flags = 0;
417 
418 	if (oflags & O_TMPFILE)
419 		flags |= DELETE;
420 
421 	if ((oflags & O_ACCMODE) == O_RDONLY)
422 		return flags | GENERIC_READ;
423 	if ((oflags & O_ACCMODE) == O_WRONLY) {
424 		return flags | (rdwr_for_fscache == 1 ?
425 				(GENERIC_READ | GENERIC_WRITE) : GENERIC_WRITE);
426 	}
427 	if ((oflags & O_ACCMODE) == O_RDWR) {
428 		/* GENERIC_ALL is too much permission to request
429 		   can cause unnecessary access denied on create */
430 		/* return GENERIC_ALL; */
431 		return flags | GENERIC_READ | GENERIC_WRITE;
432 	}
433 
434 	return flags | READ_CONTROL | FILE_WRITE_ATTRIBUTES |
435 		FILE_READ_ATTRIBUTES | FILE_WRITE_EA | FILE_APPEND_DATA |
436 		FILE_WRITE_DATA | FILE_READ_DATA;
437 }
438 
439 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
440 static u32 cifs_posix_convert_flags(unsigned int flags)
441 {
442 	u32 posix_flags = 0;
443 
444 	if ((flags & O_ACCMODE) == O_RDONLY)
445 		posix_flags = SMB_O_RDONLY;
446 	else if ((flags & O_ACCMODE) == O_WRONLY)
447 		posix_flags = SMB_O_WRONLY;
448 	else if ((flags & O_ACCMODE) == O_RDWR)
449 		posix_flags = SMB_O_RDWR;
450 
451 	if (flags & O_CREAT) {
452 		posix_flags |= SMB_O_CREAT;
453 		if (flags & O_EXCL)
454 			posix_flags |= SMB_O_EXCL;
455 	} else if (flags & O_EXCL)
456 		cifs_dbg(FYI, "Application %s pid %d has incorrectly set O_EXCL flag but not O_CREAT on file open. Ignoring O_EXCL\n",
457 			 current->comm, current->tgid);
458 
459 	if (flags & O_TRUNC)
460 		posix_flags |= SMB_O_TRUNC;
461 	/* be safe and imply O_SYNC for O_DSYNC */
462 	if (flags & O_DSYNC)
463 		posix_flags |= SMB_O_SYNC;
464 	if (flags & O_DIRECTORY)
465 		posix_flags |= SMB_O_DIRECTORY;
466 	if (flags & O_NOFOLLOW)
467 		posix_flags |= SMB_O_NOFOLLOW;
468 	if (flags & O_DIRECT)
469 		posix_flags |= SMB_O_DIRECT;
470 
471 	return posix_flags;
472 }
473 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
474 
475 static inline int cifs_get_disposition(unsigned int flags)
476 {
477 	if ((flags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL))
478 		return FILE_CREATE;
479 	else if ((flags & (O_CREAT | O_TRUNC)) == (O_CREAT | O_TRUNC))
480 		return FILE_OVERWRITE_IF;
481 	else if ((flags & O_CREAT) == O_CREAT)
482 		return FILE_OPEN_IF;
483 	else if ((flags & O_TRUNC) == O_TRUNC)
484 		return FILE_OVERWRITE;
485 	else
486 		return FILE_OPEN;
487 }
488 
489 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
490 int cifs_posix_open(const char *full_path, struct inode **pinode,
491 			struct super_block *sb, int mode, unsigned int f_flags,
492 			__u32 *poplock, __u16 *pnetfid, unsigned int xid)
493 {
494 	int rc;
495 	FILE_UNIX_BASIC_INFO *presp_data;
496 	__u32 posix_flags = 0;
497 	struct cifs_sb_info *cifs_sb = CIFS_SB(sb);
498 	struct cifs_fattr fattr;
499 	struct tcon_link *tlink;
500 	struct cifs_tcon *tcon;
501 
502 	cifs_dbg(FYI, "posix open %s\n", full_path);
503 
504 	presp_data = kzalloc_obj(FILE_UNIX_BASIC_INFO);
505 	if (presp_data == NULL)
506 		return -ENOMEM;
507 
508 	tlink = cifs_sb_tlink(cifs_sb);
509 	if (IS_ERR(tlink)) {
510 		rc = PTR_ERR(tlink);
511 		goto posix_open_ret;
512 	}
513 
514 	tcon = tlink_tcon(tlink);
515 	mode &= ~current_umask();
516 
517 	posix_flags = cifs_posix_convert_flags(f_flags);
518 	rc = CIFSPOSIXCreate(xid, tcon, posix_flags, mode, pnetfid, presp_data,
519 			     poplock, full_path, cifs_remap(cifs_sb));
520 	cifs_put_tlink(tlink);
521 
522 	if (rc)
523 		goto posix_open_ret;
524 
525 	if (presp_data->Type == cpu_to_le32(-1))
526 		goto posix_open_ret; /* open ok, caller does qpathinfo */
527 
528 	if (!pinode)
529 		goto posix_open_ret; /* caller does not need info */
530 
531 	cifs_unix_basic_to_fattr(&fattr, presp_data, cifs_sb);
532 
533 	/* get new inode and set it up */
534 	if (*pinode == NULL) {
535 		cifs_fill_uniqueid(sb, &fattr);
536 		*pinode = cifs_iget(sb, &fattr);
537 		if (!*pinode) {
538 			rc = -ENOMEM;
539 			goto posix_open_ret;
540 		}
541 	} else {
542 		cifs_revalidate_mapping(*pinode);
543 		rc = cifs_fattr_to_inode(*pinode, &fattr, false);
544 	}
545 
546 posix_open_ret:
547 	kfree(presp_data);
548 	return rc;
549 }
550 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
551 
552 static int cifs_nt_open(const char *full_path, struct inode *inode, struct cifs_sb_info *cifs_sb,
553 			struct cifs_tcon *tcon, unsigned int f_flags, __u32 *oplock,
554 			struct cifs_fid *fid, unsigned int xid, struct cifs_open_info_data *buf)
555 {
556 	int rc;
557 	int desired_access;
558 	int disposition;
559 	int create_options = CREATE_NOT_DIR;
560 	struct TCP_Server_Info *server = tcon->ses->server;
561 	struct cifs_open_parms oparms;
562 	int rdwr_for_fscache = 0;
563 
564 	if (!server->ops->open)
565 		return -ENOSYS;
566 
567 	/* If we're caching, we need to be able to fill in around partial writes. */
568 	if (cifs_fscache_enabled(inode) && (f_flags & O_ACCMODE) == O_WRONLY)
569 		rdwr_for_fscache = 1;
570 
571 	desired_access = cifs_convert_flags(f_flags, rdwr_for_fscache);
572 
573 /*********************************************************************
574  *  open flag mapping table:
575  *
576  *	POSIX Flag            CIFS Disposition
577  *	----------            ----------------
578  *	O_CREAT               FILE_OPEN_IF
579  *	O_CREAT | O_EXCL      FILE_CREATE
580  *	O_CREAT | O_TRUNC     FILE_OVERWRITE_IF
581  *	O_TRUNC               FILE_OVERWRITE
582  *	none of the above     FILE_OPEN
583  *
584  *	Note that there is not a direct match between disposition
585  *	FILE_SUPERSEDE (ie create whether or not file exists although
586  *	O_CREAT | O_TRUNC is similar but truncates the existing
587  *	file rather than creating a new file as FILE_SUPERSEDE does
588  *	(which uses the attributes / metadata passed in on open call)
589  *?
590  *?  O_SYNC is a reasonable match to CIFS writethrough flag
591  *?  and the read write flags match reasonably.  O_LARGEFILE
592  *?  is irrelevant because largefile support is always used
593  *?  by this client. Flags O_APPEND, O_DIRECT, O_DIRECTORY,
594  *	 O_FASYNC, O_NOFOLLOW, O_NONBLOCK need further investigation
595  *********************************************************************/
596 
597 	disposition = cifs_get_disposition(f_flags);
598 	/* BB pass O_SYNC flag through on file attributes .. BB */
599 	create_options |= cifs_open_create_options(f_flags, create_options);
600 
601 retry_open:
602 	oparms = (struct cifs_open_parms) {
603 		.tcon = tcon,
604 		.cifs_sb = cifs_sb,
605 		.desired_access = desired_access,
606 		.create_options = cifs_create_options(cifs_sb, create_options),
607 		.disposition = disposition,
608 		.path = full_path,
609 		.fid = fid,
610 	};
611 
612 	rc = server->ops->open(xid, &oparms, oplock, buf);
613 	if (rc) {
614 		if (rc == -EACCES && rdwr_for_fscache == 1) {
615 			desired_access = cifs_convert_flags(f_flags, 0);
616 			rdwr_for_fscache = 2;
617 			goto retry_open;
618 		}
619 		return rc;
620 	}
621 	if (rdwr_for_fscache == 2)
622 		cifs_invalidate_cache(inode, FSCACHE_INVAL_DIO_WRITE);
623 
624 	if (server->vals->protocol_id > SMB20_PROT_ID &&
625 	    *oplock != SMB2_OPLOCK_LEVEL_NONE)
626 		CIFS_I(inode)->lease_granted = true;
627 
628 	/* TODO: Add support for calling posix query info but with passing in fid */
629 	if (tcon->unix_ext)
630 		rc = cifs_get_inode_info_unix(&inode, full_path, inode->i_sb,
631 					      xid);
632 	else
633 		rc = cifs_get_inode_info(&inode, full_path, buf, inode->i_sb,
634 					 xid, fid);
635 
636 	if (rc) {
637 		server->ops->close(xid, tcon, fid);
638 		if (rc == -ESTALE)
639 			rc = -EOPENSTALE;
640 	}
641 
642 	return rc;
643 }
644 
645 static bool
646 cifs_has_mand_locks(struct cifsInodeInfo *cinode)
647 {
648 	struct cifs_fid_locks *cur;
649 	bool has_locks = false;
650 
651 	down_read(&cinode->lock_sem);
652 	list_for_each_entry(cur, &cinode->llist, llist) {
653 		if (!list_empty(&cur->locks)) {
654 			has_locks = true;
655 			break;
656 		}
657 	}
658 	up_read(&cinode->lock_sem);
659 	return has_locks;
660 }
661 
662 void
663 cifs_down_write(struct rw_semaphore *sem)
664 {
665 	while (!down_write_trylock(sem))
666 		msleep(10);
667 }
668 
669 static void cifsFileInfo_put_work(struct work_struct *work);
670 void serverclose_work(struct work_struct *work);
671 
672 struct cifsFileInfo *cifs_new_fileinfo(struct cifs_fid *fid, struct file *file,
673 				       struct tcon_link *tlink, __u32 oplock,
674 				       const char *symlink_target)
675 {
676 	struct dentry *dentry = file_dentry(file);
677 	struct inode *inode = d_inode(dentry);
678 	struct cifsInodeInfo *cinode = CIFS_I(inode);
679 	struct cifsFileInfo *cfile;
680 	struct cifs_fid_locks *fdlocks;
681 	struct cifs_tcon *tcon = tlink_tcon(tlink);
682 	struct TCP_Server_Info *server = tcon->ses->server;
683 
684 	cfile = kzalloc_obj(struct cifsFileInfo);
685 	if (cfile == NULL)
686 		return cfile;
687 
688 	fdlocks = kzalloc_obj(struct cifs_fid_locks);
689 	if (!fdlocks) {
690 		kfree(cfile);
691 		return NULL;
692 	}
693 
694 	if (symlink_target) {
695 		cfile->symlink_target = kstrdup(symlink_target, GFP_KERNEL);
696 		if (!cfile->symlink_target) {
697 			kfree(fdlocks);
698 			kfree(cfile);
699 			return NULL;
700 		}
701 	}
702 
703 	INIT_LIST_HEAD(&fdlocks->locks);
704 	fdlocks->cfile = cfile;
705 	cfile->llist = fdlocks;
706 
707 	cfile->count = 1;
708 	cfile->pid = current->tgid;
709 	cfile->uid = current_fsuid();
710 	cfile->dentry = dget(dentry);
711 	cfile->f_flags = file->f_flags;
712 	cfile->invalidHandle = false;
713 	cfile->deferred_close_scheduled = false;
714 	cfile->status_file_deleted = file->f_flags & O_TMPFILE;
715 	cfile->tlink = cifs_get_tlink(tlink);
716 	INIT_WORK(&cfile->oplock_break, cifs_oplock_break);
717 	INIT_WORK(&cfile->put, cifsFileInfo_put_work);
718 	INIT_WORK(&cfile->serverclose, serverclose_work);
719 	INIT_DELAYED_WORK(&cfile->deferred, smb2_deferred_work_close);
720 	mutex_init(&cfile->fh_mutex);
721 	spin_lock_init(&cfile->file_info_lock);
722 
723 	/*
724 	 * If the server returned a read oplock and we have mandatory brlocks,
725 	 * set oplock level to None.
726 	 */
727 	if (server->ops->is_read_op(oplock) && cifs_has_mand_locks(cinode)) {
728 		cifs_dbg(FYI, "Reset oplock val from read to None due to mand locks\n");
729 		oplock = 0;
730 	}
731 
732 	cifs_down_write(&cinode->lock_sem);
733 	list_add(&fdlocks->llist, &cinode->llist);
734 	up_write(&cinode->lock_sem);
735 
736 	spin_lock(&tcon->open_file_lock);
737 	if (fid->pending_open->oplock != CIFS_OPLOCK_NO_CHANGE && oplock)
738 		oplock = fid->pending_open->oplock;
739 	list_del(&fid->pending_open->olist);
740 
741 	list_add(&cfile->tlist, &tcon->openFileList);
742 	atomic_inc(&tcon->num_local_opens);
743 
744 	/* if readable file instance put first in list*/
745 	spin_lock(&cinode->open_file_lock);
746 	if (file->f_flags & O_TMPFILE)
747 		set_bit(CIFS_INO_TMPFILE, &cinode->flags);
748 	fid->purge_cache = false;
749 	server->ops->set_fid(cfile, fid, oplock);
750 
751 	if (file->f_mode & FMODE_READ)
752 		list_add(&cfile->flist, &cinode->openFileList);
753 	else
754 		list_add_tail(&cfile->flist, &cinode->openFileList);
755 	spin_unlock(&cinode->open_file_lock);
756 	spin_unlock(&tcon->open_file_lock);
757 
758 	if (fid->purge_cache)
759 		cifs_zap_mapping(inode);
760 
761 	file->private_data = cfile;
762 	return cfile;
763 }
764 
765 struct cifsFileInfo *
766 cifsFileInfo_get(struct cifsFileInfo *cifs_file)
767 {
768 	spin_lock(&cifs_file->file_info_lock);
769 	cifsFileInfo_get_locked(cifs_file);
770 	spin_unlock(&cifs_file->file_info_lock);
771 	return cifs_file;
772 }
773 
774 static void cifsFileInfo_put_final(struct cifsFileInfo *cifs_file)
775 {
776 	struct inode *inode = d_inode(cifs_file->dentry);
777 	struct cifsInodeInfo *cifsi = CIFS_I(inode);
778 	struct cifsLockInfo *li, *tmp;
779 
780 	/*
781 	 * Delete any outstanding lock records. We'll lose them when the file
782 	 * is closed anyway.
783 	 */
784 	cifs_down_write(&cifsi->lock_sem);
785 	list_for_each_entry_safe(li, tmp, &cifs_file->llist->locks, llist) {
786 		list_del(&li->llist);
787 		cifs_del_lock_waiters(li);
788 		kfree(li);
789 	}
790 	list_del(&cifs_file->llist->llist);
791 	kfree(cifs_file->llist);
792 	up_write(&cifsi->lock_sem);
793 
794 	cifs_put_tlink(cifs_file->tlink);
795 	dput(cifs_file->dentry);
796 	kfree(cifs_file->symlink_target);
797 	kfree(cifs_file);
798 }
799 
800 static void cifsFileInfo_put_work(struct work_struct *work)
801 {
802 	struct cifsFileInfo *cifs_file = container_of(work,
803 			struct cifsFileInfo, put);
804 
805 	cifsFileInfo_put_final(cifs_file);
806 }
807 
808 void serverclose_work(struct work_struct *work)
809 {
810 	struct cifsFileInfo *cifs_file = container_of(work,
811 			struct cifsFileInfo, serverclose);
812 
813 	struct cifs_tcon *tcon = tlink_tcon(cifs_file->tlink);
814 
815 	struct TCP_Server_Info *server = tcon->ses->server;
816 	int rc = 0;
817 	int retries = 0;
818 	int MAX_RETRIES = 4;
819 
820 	do {
821 		if (server->ops->close_getattr)
822 			rc = server->ops->close_getattr(0, tcon, cifs_file);
823 		else if (server->ops->close)
824 			rc = server->ops->close(0, tcon, &cifs_file->fid);
825 
826 		if (rc == -EBUSY || rc == -EAGAIN) {
827 			retries++;
828 			msleep(250);
829 		}
830 	} while ((rc == -EBUSY || rc == -EAGAIN) && (retries < MAX_RETRIES)
831 	);
832 
833 	if (retries == MAX_RETRIES)
834 		pr_warn("Serverclose failed %d times, giving up\n", MAX_RETRIES);
835 
836 	if (cifs_file->offload)
837 		queue_work(fileinfo_put_wq, &cifs_file->put);
838 	else
839 		cifsFileInfo_put_final(cifs_file);
840 }
841 
842 /**
843  * cifsFileInfo_put - release a reference of file priv data
844  *
845  * Always potentially wait for oplock handler. See _cifsFileInfo_put().
846  *
847  * @cifs_file:	cifs/smb3 specific info (eg refcounts) for an open file
848  */
849 void cifsFileInfo_put(struct cifsFileInfo *cifs_file)
850 {
851 	_cifsFileInfo_put(cifs_file, true, true);
852 }
853 
854 /**
855  * _cifsFileInfo_put - release a reference of file priv data
856  *
857  * This may involve closing the filehandle @cifs_file out on the
858  * server. Must be called without holding tcon->open_file_lock,
859  * cinode->open_file_lock and cifs_file->file_info_lock.
860  *
861  * If @wait_for_oplock_handler is true and we are releasing the last
862  * reference, wait for any running oplock break handler of the file
863  * and cancel any pending one.
864  *
865  * @cifs_file:	cifs/smb3 specific info (eg refcounts) for an open file
866  * @wait_oplock_handler: must be false if called from oplock_break_handler
867  * @offload:	not offloaded on close and oplock breaks
868  *
869  */
870 void _cifsFileInfo_put(struct cifsFileInfo *cifs_file,
871 		       bool wait_oplock_handler, bool offload)
872 {
873 	struct inode *inode = d_inode(cifs_file->dentry);
874 	struct cifs_tcon *tcon = tlink_tcon(cifs_file->tlink);
875 	struct TCP_Server_Info *server = tcon->ses->server;
876 	struct cifsInodeInfo *cifsi = CIFS_I(inode);
877 	struct super_block *sb = inode->i_sb;
878 	struct cifs_sb_info *cifs_sb = CIFS_SB(sb);
879 	struct cifs_fid fid = {};
880 	struct cifs_pending_open open;
881 	bool oplock_break_cancelled;
882 	bool serverclose_offloaded = false;
883 
884 	spin_lock(&tcon->open_file_lock);
885 	spin_lock(&cifsi->open_file_lock);
886 	spin_lock(&cifs_file->file_info_lock);
887 
888 	cifs_file->offload = offload;
889 	if (--cifs_file->count > 0) {
890 		spin_unlock(&cifs_file->file_info_lock);
891 		spin_unlock(&cifsi->open_file_lock);
892 		spin_unlock(&tcon->open_file_lock);
893 		return;
894 	}
895 	spin_unlock(&cifs_file->file_info_lock);
896 
897 	if (server->ops->get_lease_key)
898 		server->ops->get_lease_key(inode, &fid);
899 
900 	/* store open in pending opens to make sure we don't miss lease break */
901 	cifs_add_pending_open_locked(&fid, cifs_file->tlink, &open);
902 
903 	/* remove it from the lists */
904 	list_del(&cifs_file->flist);
905 	list_del(&cifs_file->tlist);
906 	atomic_dec(&tcon->num_local_opens);
907 
908 	if (list_empty(&cifsi->openFileList)) {
909 		cifs_dbg(FYI, "closing last open instance for inode %p\n",
910 			 d_inode(cifs_file->dentry));
911 		/*
912 		 * In strict cache mode we need invalidate mapping on the last
913 		 * close  because it may cause a error when we open this file
914 		 * again and get at least level II oplock.
915 		 */
916 		if (cifs_sb_flags(cifs_sb) & CIFS_MOUNT_STRICT_IO)
917 			set_bit(CIFS_INO_INVALID_MAPPING, &cifsi->flags);
918 		cifs_set_oplock_level(cifsi, 0);
919 	}
920 
921 	if (OPEN_FMODE(cifs_file->f_flags) & FMODE_WRITE) {
922 		/* Stamp while open_file_lock is held; covers all close paths
923 		 * including background I/O. Pairs with smp_load_acquire() in
924 		 * is_size_safe_to_change().
925 		 */
926 		smp_store_release(&cifsi->time_last_write, jiffies);
927 	}
928 
929 	spin_unlock(&cifsi->open_file_lock);
930 	spin_unlock(&tcon->open_file_lock);
931 
932 	oplock_break_cancelled = wait_oplock_handler ?
933 		cancel_work_sync(&cifs_file->oplock_break) : false;
934 
935 	if (!tcon->need_reconnect && !cifs_file->invalidHandle) {
936 		struct TCP_Server_Info *server = tcon->ses->server;
937 		unsigned int xid;
938 		int rc = 0;
939 
940 		xid = get_xid();
941 		if (server->ops->close_getattr)
942 			rc = server->ops->close_getattr(xid, tcon, cifs_file);
943 		else if (server->ops->close)
944 			rc = server->ops->close(xid, tcon, &cifs_file->fid);
945 		_free_xid(xid);
946 
947 		if (rc == -EBUSY || rc == -EAGAIN) {
948 			// Server close failed, hence offloading it as an async op
949 			queue_work(serverclose_wq, &cifs_file->serverclose);
950 			serverclose_offloaded = true;
951 		}
952 	}
953 
954 	if (oplock_break_cancelled)
955 		cifs_done_oplock_break(cifsi);
956 
957 	cifs_del_pending_open(&open);
958 
959 	// if serverclose has been offloaded to wq (on failure), it will
960 	// handle offloading put as well. If serverclose not offloaded,
961 	// we need to handle offloading put here.
962 	if (!serverclose_offloaded) {
963 		if (offload)
964 			queue_work(fileinfo_put_wq, &cifs_file->put);
965 		else
966 			cifsFileInfo_put_final(cifs_file);
967 	}
968 }
969 
970 int cifs_file_flush(const unsigned int xid, struct inode *inode,
971 		    struct cifsFileInfo *cfile)
972 {
973 	struct cifs_sb_info *cifs_sb = CIFS_SB(inode);
974 	struct cifs_tcon *tcon;
975 	int rc;
976 
977 	if (cifs_sb_flags(cifs_sb) & CIFS_MOUNT_NOSSYNC)
978 		return 0;
979 
980 	if (cfile && (OPEN_FMODE(cfile->f_flags) & FMODE_WRITE)) {
981 		tcon = tlink_tcon(cfile->tlink);
982 		return tcon->ses->server->ops->flush(xid, tcon,
983 						     &cfile->fid);
984 	}
985 	rc = cifs_get_writable_file(CIFS_I(inode), FIND_ANY, &cfile);
986 	if (!rc) {
987 		tcon = tlink_tcon(cfile->tlink);
988 		rc = tcon->ses->server->ops->flush(xid, tcon, &cfile->fid);
989 		cifsFileInfo_put(cfile);
990 	} else if (rc == -EBADF) {
991 		rc = 0;
992 	}
993 	return rc;
994 }
995 
996 static int cifs_do_truncate(const unsigned int xid, struct dentry *dentry)
997 {
998 	struct cifsInodeInfo *cinode = CIFS_I(d_inode(dentry));
999 	struct inode *inode = d_inode(dentry);
1000 	struct cifsFileInfo *cfile = NULL;
1001 	struct TCP_Server_Info *server;
1002 	struct cifs_tcon *tcon;
1003 	int rc;
1004 
1005 	rc = inode_lock_killable(inode);
1006 	if (rc)
1007 		return -ERESTARTSYS;
1008 
1009 	filemap_invalidate_lock(inode->i_mapping);
1010 
1011 	rc = filemap_write_and_wait(inode->i_mapping);
1012 	if (is_interrupt_error(rc)) {
1013 		rc = -ERESTARTSYS;
1014 		goto out;
1015 	}
1016 	mapping_set_error(inode->i_mapping, rc);
1017 
1018 	netfs_wait_for_outstanding_io(inode);
1019 
1020 	cfile = find_writable_file(cinode, FIND_FSUID_ONLY);
1021 	rc = cifs_file_flush(xid, inode, cfile);
1022 	if (!rc) {
1023 		if (cfile) {
1024 			struct netfs_inode *ictx = netfs_inode(inode);
1025 			loff_t old_size = i_size_read(inode);
1026 
1027 			tcon = tlink_tcon(cfile->tlink);
1028 			server = tcon->ses->server;
1029 			netfs_wb_begin(ictx, false);
1030 			rc = server->ops->set_file_size(xid, tcon,
1031 							cfile, 0, false);
1032 			if (!rc) {
1033 				netfs_resize_file(&cinode->netfs, 0, true);
1034 				cifs_setsize(inode, old_size, 0);
1035 				cifs_invalidate_cache(inode, 0);
1036 			}
1037 			netfs_wb_end(ictx);
1038 		} else {
1039 			/*
1040 			 * No cached handle; evict stale pages so they can't
1041 			 * be served after the file is later extended; let
1042 			 * the server's O_TRUNC open response set the i_size
1043 			 */
1044 			truncate_inode_pages(inode->i_mapping, 0);
1045 			cifs_invalidate_cache(inode, 0);
1046 		}
1047 	}
1048 
1049 out:
1050 	filemap_invalidate_unlock(inode->i_mapping);
1051 	inode_unlock(inode);
1052 	if (cfile)
1053 		cifsFileInfo_put(cfile);
1054 	return rc;
1055 }
1056 
1057 int cifs_open(struct inode *inode, struct file *file)
1058 
1059 {
1060 	struct cifs_sb_info *cifs_sb = CIFS_SB(inode);
1061 	struct cifs_open_info_data data = {};
1062 	struct cifsFileInfo *cfile = NULL;
1063 	struct TCP_Server_Info *server;
1064 	struct cifs_pending_open open;
1065 	bool posix_open_ok = false;
1066 	struct cifs_fid fid = {};
1067 	struct tcon_link *tlink;
1068 	struct cifs_tcon *tcon;
1069 	const char *full_path;
1070 	unsigned int sbflags;
1071 	int rc = -EACCES;
1072 	unsigned int xid;
1073 	__u32 oplock;
1074 	void *page;
1075 
1076 	xid = get_xid();
1077 
1078 	if (unlikely(cifs_forced_shutdown(cifs_sb))) {
1079 		free_xid(xid);
1080 		return smb_EIO(smb_eio_trace_forced_shutdown);
1081 	}
1082 
1083 	tlink = cifs_sb_tlink(cifs_sb);
1084 	if (IS_ERR(tlink)) {
1085 		free_xid(xid);
1086 		return PTR_ERR(tlink);
1087 	}
1088 	tcon = tlink_tcon(tlink);
1089 	server = tcon->ses->server;
1090 
1091 	page = alloc_dentry_path();
1092 	full_path = build_path_from_dentry(file_dentry(file), page);
1093 	if (IS_ERR(full_path)) {
1094 		rc = PTR_ERR(full_path);
1095 		goto out;
1096 	}
1097 
1098 	cifs_dbg(FYI, "inode = 0x%p file flags are 0x%x for %s\n",
1099 		 inode, file->f_flags, full_path);
1100 
1101 	sbflags = cifs_sb_flags(cifs_sb);
1102 	if ((file->f_flags & O_DIRECT) && (sbflags & CIFS_MOUNT_STRICT_IO)) {
1103 		if (sbflags & CIFS_MOUNT_NO_BRL)
1104 			file->f_op = &cifs_file_direct_nobrl_ops;
1105 		else
1106 			file->f_op = &cifs_file_direct_ops;
1107 	}
1108 
1109 	if (file->f_flags & O_TRUNC) {
1110 		rc = cifs_do_truncate(xid, file_dentry(file));
1111 		if (rc)
1112 			goto out;
1113 	}
1114 
1115 	/* Get the cached handle as SMB2 close is deferred */
1116 	if (OPEN_FMODE(file->f_flags) & FMODE_WRITE) {
1117 		rc = __cifs_get_writable_file(CIFS_I(inode),
1118 					      FIND_FSUID_ONLY |
1119 					      FIND_NO_PENDING_DELETE |
1120 					      FIND_OPEN_FLAGS,
1121 					      file->f_flags, &cfile);
1122 	} else {
1123 		cfile = __find_readable_file(CIFS_I(inode),
1124 					     FIND_NO_PENDING_DELETE |
1125 					     FIND_OPEN_FLAGS,
1126 					     file->f_flags);
1127 		rc = cfile ? 0 : -ENOENT;
1128 	}
1129 	if (rc == 0) {
1130 		trace_smb3_open_cached(xid, tcon->tid, tcon->ses->Suid,
1131 				       cfile->fid.persistent_fid,
1132 				       file->f_flags, cfile->f_flags);
1133 		file->private_data = cfile;
1134 		spin_lock(&CIFS_I(inode)->deferred_lock);
1135 		cifs_del_deferred_close(cfile);
1136 		spin_unlock(&CIFS_I(inode)->deferred_lock);
1137 		goto use_cache;
1138 	}
1139 	/* hard link on the deferred close file */
1140 	rc = cifs_get_hardlink_path(tcon, inode, file);
1141 	if (rc)
1142 		cifs_close_deferred_file(CIFS_I(inode));
1143 
1144 	if (server->oplocks)
1145 		oplock = REQ_OPLOCK;
1146 	else
1147 		oplock = 0;
1148 
1149 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
1150 	if (!tcon->broken_posix_open && tcon->unix_ext &&
1151 	    cap_unix(tcon->ses) && (CIFS_UNIX_POSIX_PATH_OPS_CAP &
1152 				le64_to_cpu(tcon->fsUnixInfo.Capability))) {
1153 		/* can not refresh inode info since size could be stale */
1154 		rc = cifs_posix_open(full_path, &inode, inode->i_sb,
1155 				cifs_sb->ctx->file_mode /* ignored */,
1156 				file->f_flags, &oplock, &fid.netfid, xid);
1157 		if (rc == 0) {
1158 			cifs_dbg(FYI, "posix open succeeded\n");
1159 			posix_open_ok = true;
1160 		} else if ((rc == -EINVAL) || (rc == -EOPNOTSUPP)) {
1161 			if (tcon->ses->serverNOS)
1162 				cifs_dbg(VFS, "server %s of type %s returned unexpected error on SMB posix open, disabling posix open support. Check if server update available.\n",
1163 					 tcon->ses->ip_addr,
1164 					 tcon->ses->serverNOS);
1165 			tcon->broken_posix_open = true;
1166 		} else if ((rc != -EIO) && (rc != -EREMOTE) &&
1167 			 (rc != -EOPNOTSUPP)) /* path not found or net err */
1168 			goto out;
1169 		/*
1170 		 * Else fallthrough to retry open the old way on network i/o
1171 		 * or DFS errors.
1172 		 */
1173 	}
1174 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
1175 
1176 	if (server->ops->get_lease_key)
1177 		server->ops->get_lease_key(inode, &fid);
1178 
1179 	cifs_add_pending_open(&fid, tlink, &open);
1180 
1181 	if (!posix_open_ok) {
1182 		if (server->ops->get_lease_key)
1183 			server->ops->get_lease_key(inode, &fid);
1184 
1185 		rc = cifs_nt_open(full_path, inode, cifs_sb, tcon, file->f_flags, &oplock, &fid,
1186 				  xid, &data);
1187 		if (rc) {
1188 			cifs_del_pending_open(&open);
1189 			goto out;
1190 		}
1191 	}
1192 
1193 	cfile = cifs_new_fileinfo(&fid, file, tlink, oplock, data.symlink_target);
1194 	if (cfile == NULL) {
1195 		if (server->ops->close)
1196 			server->ops->close(xid, tcon, &fid);
1197 		cifs_del_pending_open(&open);
1198 		rc = -ENOMEM;
1199 		goto out;
1200 	}
1201 
1202 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
1203 	if ((oplock & CIFS_CREATE_ACTION) && !posix_open_ok && tcon->unix_ext) {
1204 		/*
1205 		 * Time to set mode which we can not set earlier due to
1206 		 * problems creating new read-only files.
1207 		 */
1208 		struct cifs_unix_set_info_args args = {
1209 			.mode	= inode->i_mode,
1210 			.uid	= INVALID_UID, /* no change */
1211 			.gid	= INVALID_GID, /* no change */
1212 			.ctime	= NO_CHANGE_64,
1213 			.atime	= NO_CHANGE_64,
1214 			.mtime	= NO_CHANGE_64,
1215 			.device	= 0,
1216 		};
1217 		CIFSSMBUnixSetFileInfo(xid, tcon, &args, fid.netfid,
1218 				       cfile->pid);
1219 	}
1220 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
1221 
1222 use_cache:
1223 	fscache_use_cookie(cifs_inode_cookie(file_inode(file)),
1224 			   file->f_mode & FMODE_WRITE);
1225 	if (!(file->f_flags & O_DIRECT))
1226 		goto out;
1227 	if ((file->f_flags & (O_ACCMODE | O_APPEND)) == O_RDONLY)
1228 		goto out;
1229 	cifs_invalidate_cache(file_inode(file), FSCACHE_INVAL_DIO_WRITE);
1230 
1231 out:
1232 	free_dentry_path(page);
1233 	free_xid(xid);
1234 	cifs_put_tlink(tlink);
1235 	cifs_free_open_info(&data);
1236 	return rc;
1237 }
1238 
1239 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
1240 static int cifs_push_posix_locks(struct cifsFileInfo *cfile);
1241 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
1242 
1243 /*
1244  * Try to reacquire byte range locks that were released when session
1245  * to server was lost.
1246  */
1247 static int
1248 cifs_relock_file(struct cifsFileInfo *cfile)
1249 {
1250 	struct cifsInodeInfo *cinode = CIFS_I(d_inode(cfile->dentry));
1251 	struct cifs_tcon *tcon = tlink_tcon(cfile->tlink);
1252 	int rc = 0;
1253 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
1254 	struct cifs_sb_info *cifs_sb = CIFS_SB(cinode);
1255 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
1256 
1257 	down_read_nested(&cinode->lock_sem, SINGLE_DEPTH_NESTING);
1258 	if (cinode->can_cache_brlcks) {
1259 		/* can cache locks - no need to relock */
1260 		up_read(&cinode->lock_sem);
1261 		return rc;
1262 	}
1263 
1264 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
1265 	if (cap_unix(tcon->ses) &&
1266 	    (CIFS_UNIX_FCNTL_CAP & le64_to_cpu(tcon->fsUnixInfo.Capability)) &&
1267 	    ((cifs_sb_flags(cifs_sb) & CIFS_MOUNT_NOPOSIXBRL) == 0))
1268 		rc = cifs_push_posix_locks(cfile);
1269 	else
1270 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
1271 		rc = tcon->ses->server->ops->push_mand_locks(cfile);
1272 
1273 	up_read(&cinode->lock_sem);
1274 	return rc;
1275 }
1276 
1277 static int
1278 cifs_reopen_file(struct cifsFileInfo *cfile, bool can_flush)
1279 {
1280 	int rc = -EACCES;
1281 	unsigned int xid;
1282 	__u32 oplock;
1283 	struct cifs_sb_info *cifs_sb;
1284 	struct cifs_tcon *tcon;
1285 	struct TCP_Server_Info *server;
1286 	struct cifsInodeInfo *cinode;
1287 	struct inode *inode;
1288 	void *page;
1289 	const char *full_path;
1290 	int desired_access;
1291 	int disposition = FILE_OPEN;
1292 	int create_options = CREATE_NOT_DIR;
1293 	struct cifs_open_parms oparms;
1294 	int rdwr_for_fscache = 0;
1295 
1296 	xid = get_xid();
1297 	mutex_lock(&cfile->fh_mutex);
1298 	if (!cfile->invalidHandle) {
1299 		mutex_unlock(&cfile->fh_mutex);
1300 		free_xid(xid);
1301 		return 0;
1302 	}
1303 
1304 	inode = d_inode(cfile->dentry);
1305 	cifs_sb = CIFS_SB(inode->i_sb);
1306 	tcon = tlink_tcon(cfile->tlink);
1307 	server = tcon->ses->server;
1308 
1309 	/*
1310 	 * Can not grab rename sem here because various ops, including those
1311 	 * that already have the rename sem can end up causing writepage to get
1312 	 * called and if the server was down that means we end up here, and we
1313 	 * can never tell if the caller already has the rename_sem.
1314 	 */
1315 	page = alloc_dentry_path();
1316 	full_path = build_path_from_dentry(cfile->dentry, page);
1317 	if (IS_ERR(full_path)) {
1318 		mutex_unlock(&cfile->fh_mutex);
1319 		free_dentry_path(page);
1320 		free_xid(xid);
1321 		return PTR_ERR(full_path);
1322 	}
1323 
1324 	cifs_dbg(FYI, "inode = 0x%p file flags 0x%x for %s\n",
1325 		 inode, cfile->f_flags, full_path);
1326 
1327 	if (tcon->ses->server->oplocks)
1328 		oplock = REQ_OPLOCK;
1329 	else
1330 		oplock = 0;
1331 
1332 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
1333 	if (tcon->unix_ext && cap_unix(tcon->ses) &&
1334 	    (CIFS_UNIX_POSIX_PATH_OPS_CAP &
1335 				le64_to_cpu(tcon->fsUnixInfo.Capability))) {
1336 		/*
1337 		 * O_CREAT, O_EXCL and O_TRUNC already had their effect on the
1338 		 * original open. Must mask them off for a reopen.
1339 		 */
1340 		unsigned int oflags = cfile->f_flags &
1341 						~(O_CREAT | O_EXCL | O_TRUNC);
1342 
1343 		rc = cifs_posix_open(full_path, NULL, inode->i_sb,
1344 				     cifs_sb->ctx->file_mode /* ignored */,
1345 				     oflags, &oplock, &cfile->fid.netfid, xid);
1346 		if (rc == 0) {
1347 			cifs_dbg(FYI, "posix reopen succeeded\n");
1348 			oparms.reconnect = true;
1349 			goto reopen_success;
1350 		}
1351 		/*
1352 		 * fallthrough to retry open the old way on errors, especially
1353 		 * in the reconnect path it is important to retry hard
1354 		 */
1355 	}
1356 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
1357 
1358 	/* If we're caching, we need to be able to fill in around partial writes. */
1359 	if (cifs_fscache_enabled(inode) && (cfile->f_flags & O_ACCMODE) == O_WRONLY)
1360 		rdwr_for_fscache = 1;
1361 
1362 	desired_access = cifs_convert_flags(cfile->f_flags, rdwr_for_fscache);
1363 	create_options |= cifs_open_create_options(cfile->f_flags,
1364 						   create_options);
1365 
1366 	if (server->ops->get_lease_key)
1367 		server->ops->get_lease_key(inode, &cfile->fid);
1368 
1369 retry_open:
1370 	oparms = (struct cifs_open_parms) {
1371 		.tcon = tcon,
1372 		.cifs_sb = cifs_sb,
1373 		.desired_access = desired_access,
1374 		.create_options = cifs_create_options(cifs_sb, create_options),
1375 		.disposition = disposition,
1376 		.path = full_path,
1377 		.fid = &cfile->fid,
1378 		.reconnect = true,
1379 	};
1380 
1381 	/*
1382 	 * Can not refresh inode by passing in file_info buf to be returned by
1383 	 * ops->open and then calling get_inode_info with returned buf since
1384 	 * file might have write behind data that needs to be flushed and server
1385 	 * version of file size can be stale. If we knew for sure that inode was
1386 	 * not dirty locally we could do this.
1387 	 */
1388 	rc = server->ops->open(xid, &oparms, &oplock, NULL);
1389 	if (rc == -ENOENT && oparms.reconnect == false) {
1390 		/* durable handle timeout is expired - open the file again */
1391 		rc = server->ops->open(xid, &oparms, &oplock, NULL);
1392 		/* indicate that we need to relock the file */
1393 		oparms.reconnect = true;
1394 	}
1395 	if (rc == -EACCES && rdwr_for_fscache == 1) {
1396 		desired_access = cifs_convert_flags(cfile->f_flags, 0);
1397 		rdwr_for_fscache = 2;
1398 		goto retry_open;
1399 	}
1400 
1401 	if (rc) {
1402 		mutex_unlock(&cfile->fh_mutex);
1403 		cifs_dbg(FYI, "cifs_reopen returned 0x%x\n", rc);
1404 		cifs_dbg(FYI, "oplock: %d\n", oplock);
1405 		goto reopen_error_exit;
1406 	}
1407 
1408 	if (rdwr_for_fscache == 2)
1409 		cifs_invalidate_cache(inode, FSCACHE_INVAL_DIO_WRITE);
1410 
1411 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
1412 reopen_success:
1413 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
1414 	cfile->invalidHandle = false;
1415 	mutex_unlock(&cfile->fh_mutex);
1416 	cinode = CIFS_I(inode);
1417 
1418 	if (can_flush) {
1419 		rc = filemap_write_and_wait(inode->i_mapping);
1420 		if (!is_interrupt_error(rc))
1421 			mapping_set_error(inode->i_mapping, rc);
1422 
1423 		if (tcon->posix_extensions) {
1424 			rc = smb311_posix_get_inode_info(&inode, full_path,
1425 							 NULL, inode->i_sb, xid);
1426 		} else if (tcon->unix_ext) {
1427 			rc = cifs_get_inode_info_unix(&inode, full_path,
1428 						      inode->i_sb, xid);
1429 		} else {
1430 			rc = cifs_get_inode_info(&inode, full_path, NULL,
1431 						 inode->i_sb, xid, NULL);
1432 		}
1433 	}
1434 	/*
1435 	 * Else we are writing out data to server already and could deadlock if
1436 	 * we tried to flush data, and since we do not know if we have data that
1437 	 * would invalidate the current end of file on the server we can not go
1438 	 * to the server to get the new inode info.
1439 	 */
1440 
1441 	/*
1442 	 * If the server returned a read oplock and we have mandatory brlocks,
1443 	 * set oplock level to None.
1444 	 */
1445 	if (server->ops->is_read_op(oplock) && cifs_has_mand_locks(cinode)) {
1446 		cifs_dbg(FYI, "Reset oplock val from read to None due to mand locks\n");
1447 		oplock = 0;
1448 	}
1449 
1450 	scoped_guard(spinlock, &cinode->open_file_lock)
1451 		server->ops->set_fid(cfile, &cfile->fid, oplock);
1452 	if (oparms.reconnect)
1453 		cifs_relock_file(cfile);
1454 
1455 reopen_error_exit:
1456 	free_dentry_path(page);
1457 	free_xid(xid);
1458 	return rc;
1459 }
1460 
1461 void smb2_deferred_work_close(struct work_struct *work)
1462 {
1463 	struct cifsFileInfo *cfile = container_of(work,
1464 			struct cifsFileInfo, deferred.work);
1465 	struct cifsInodeInfo *cinode = CIFS_I(d_inode(cfile->dentry));
1466 
1467 	spin_lock(&cinode->deferred_lock);
1468 	cifs_del_deferred_close(cfile);
1469 	cfile->deferred_close_scheduled = false;
1470 	spin_unlock(&cinode->deferred_lock);
1471 	_cifsFileInfo_put(cfile, true, false);
1472 }
1473 
1474 static bool
1475 smb2_can_defer_close(struct inode *inode, struct cifs_deferred_close *dclose)
1476 {
1477 	struct cifs_sb_info *cifs_sb = CIFS_SB(inode->i_sb);
1478 	struct cifsInodeInfo *cinode = CIFS_I(inode);
1479 	unsigned int oplock = READ_ONCE(cinode->oplock);
1480 
1481 	return cifs_sb->ctx->closetimeo && cinode->lease_granted && dclose &&
1482 		(oplock == CIFS_CACHE_RHW_FLG || oplock == CIFS_CACHE_RH_FLG) &&
1483 		!test_bit(CIFS_INO_CLOSE_ON_LOCK, &cinode->flags);
1484 
1485 }
1486 
1487 int cifs_close(struct inode *inode, struct file *file)
1488 {
1489 	struct cifsFileInfo *cfile;
1490 	struct cifsInodeInfo *cinode = CIFS_I(inode);
1491 	struct cifs_sb_info *cifs_sb = CIFS_SB(inode->i_sb);
1492 	struct cifs_deferred_close *dclose;
1493 	struct cifs_tcon *tcon;
1494 
1495 	cifs_fscache_unuse_inode_cookie(inode, file->f_mode & FMODE_WRITE);
1496 
1497 	if (file->private_data != NULL) {
1498 		cfile = file->private_data;
1499 		file->private_data = NULL;
1500 		dclose = kmalloc_obj(struct cifs_deferred_close);
1501 		if ((cfile->status_file_deleted == false) &&
1502 		    (smb2_can_defer_close(inode, dclose))) {
1503 			if (test_and_clear_bit(NETFS_ICTX_MODIFIED_ATTR, &cinode->netfs.flags)) {
1504 				inode_set_mtime_to_ts(inode,
1505 						      inode_set_ctime_current(inode));
1506 			}
1507 			spin_lock(&cinode->deferred_lock);
1508 			cifs_add_deferred_close(cfile, dclose);
1509 			if (cfile->deferred_close_scheduled &&
1510 			    delayed_work_pending(&cfile->deferred)) {
1511 				/*
1512 				 * If there is no pending work, mod_delayed_work queues new work.
1513 				 * So, Increase the ref count to avoid use-after-free.
1514 				 */
1515 				if (!mod_delayed_work(deferredclose_wq,
1516 						&cfile->deferred, cifs_sb->ctx->closetimeo))
1517 					cifsFileInfo_get(cfile);
1518 			} else {
1519 				/* Deferred close for files */
1520 				tcon = tlink_tcon(cfile->tlink);
1521 				trace_smb3_close_cached(tcon->tid, tcon->ses->Suid,
1522 						cfile->fid.persistent_fid,
1523 						cifs_sb->ctx->closetimeo);
1524 				/*
1525 				 * Each queued execution owns one reference.
1526 				 * If nothing was queued, the reference of
1527 				 * the closing file is dropped below.
1528 				 */
1529 				if (queue_delayed_work(deferredclose_wq,
1530 						       &cfile->deferred,
1531 						       cifs_sb->ctx->closetimeo)) {
1532 					cfile->deferred_close_scheduled = true;
1533 					spin_unlock(&cinode->deferred_lock);
1534 					return 0;
1535 				}
1536 			}
1537 			spin_unlock(&cinode->deferred_lock);
1538 			_cifsFileInfo_put(cfile, true, false);
1539 		} else {
1540 			_cifsFileInfo_put(cfile, true, false);
1541 			kfree(dclose);
1542 		}
1543 	}
1544 
1545 	/* return code from the ->release op is always ignored */
1546 	return 0;
1547 }
1548 
1549 void
1550 cifs_reopen_persistent_handles(struct cifs_tcon *tcon)
1551 {
1552 	struct cifsFileInfo *open_file, *tmp;
1553 	LIST_HEAD(tmp_list);
1554 
1555 	if (!tcon->use_persistent || !tcon->need_reopen_files)
1556 		return;
1557 
1558 	tcon->need_reopen_files = false;
1559 
1560 	cifs_dbg(FYI, "Reopen persistent handles\n");
1561 
1562 	/* list all files open on tree connection, reopen resilient handles  */
1563 	spin_lock(&tcon->open_file_lock);
1564 	list_for_each_entry(open_file, &tcon->openFileList, tlist) {
1565 		if (!open_file->invalidHandle)
1566 			continue;
1567 		cifsFileInfo_get(open_file);
1568 		list_add_tail(&open_file->rlist, &tmp_list);
1569 	}
1570 	spin_unlock(&tcon->open_file_lock);
1571 
1572 	list_for_each_entry_safe(open_file, tmp, &tmp_list, rlist) {
1573 		if (cifs_reopen_file(open_file, false /* do not flush */))
1574 			tcon->need_reopen_files = true;
1575 		list_del_init(&open_file->rlist);
1576 		cifsFileInfo_put(open_file);
1577 	}
1578 }
1579 
1580 int cifs_closedir(struct inode *inode, struct file *file)
1581 {
1582 	int rc = 0;
1583 	unsigned int xid;
1584 	struct cifsFileInfo *cfile = file->private_data;
1585 	struct cifs_tcon *tcon;
1586 	struct TCP_Server_Info *server;
1587 	char *buf;
1588 
1589 	cifs_dbg(FYI, "Closedir inode = 0x%p\n", inode);
1590 
1591 	if (cfile == NULL)
1592 		return rc;
1593 
1594 	xid = get_xid();
1595 	tcon = tlink_tcon(cfile->tlink);
1596 	server = tcon->ses->server;
1597 
1598 	cifs_dbg(FYI, "Freeing private data in close dir\n");
1599 	spin_lock(&cfile->file_info_lock);
1600 	if (server->ops->dir_needs_close(cfile)) {
1601 		cfile->invalidHandle = true;
1602 		spin_unlock(&cfile->file_info_lock);
1603 		if (server->ops->close_dir)
1604 			rc = server->ops->close_dir(xid, tcon, &cfile->fid);
1605 		else
1606 			rc = -ENOSYS;
1607 		cifs_dbg(FYI, "Closing uncompleted readdir with rc %d\n", rc);
1608 		/* not much we can do if it fails anyway, ignore rc */
1609 		rc = 0;
1610 	} else
1611 		spin_unlock(&cfile->file_info_lock);
1612 
1613 	buf = cfile->srch_inf.ntwrk_buf_start;
1614 	if (buf) {
1615 		cifs_dbg(FYI, "closedir free smb buf in srch struct\n");
1616 		cfile->srch_inf.ntwrk_buf_start = NULL;
1617 		if (cfile->srch_inf.smallBuf)
1618 			cifs_small_buf_release(buf);
1619 		else if (cfile->srch_inf.is_dynamic_buf)
1620 			kfree(buf);
1621 		else
1622 			cifs_buf_release(buf);
1623 	}
1624 
1625 	cifs_put_tlink(cfile->tlink);
1626 	kfree(file->private_data);
1627 	file->private_data = NULL;
1628 	/* BB can we lock the filestruct while this is going on? */
1629 	free_xid(xid);
1630 	return rc;
1631 }
1632 
1633 static struct cifsLockInfo *
1634 cifs_lock_init(__u64 offset, __u64 length, __u8 type, __u16 flags)
1635 {
1636 	struct cifsLockInfo *lock =
1637 		kmalloc_obj(struct cifsLockInfo);
1638 	if (!lock)
1639 		return lock;
1640 	lock->offset = offset;
1641 	lock->length = length;
1642 	lock->type = type;
1643 	lock->pid = current->tgid;
1644 	lock->flags = flags;
1645 	INIT_LIST_HEAD(&lock->blist);
1646 	init_waitqueue_head(&lock->block_q);
1647 	return lock;
1648 }
1649 
1650 void
1651 cifs_del_lock_waiters(struct cifsLockInfo *lock)
1652 {
1653 	struct cifsLockInfo *li, *tmp;
1654 	list_for_each_entry_safe(li, tmp, &lock->blist, blist) {
1655 		list_del_init(&li->blist);
1656 		wake_up(&li->block_q);
1657 	}
1658 }
1659 
1660 #define CIFS_LOCK_OP	0
1661 #define CIFS_READ_OP	1
1662 #define CIFS_WRITE_OP	2
1663 
1664 /* @rw_check : 0 - no op, 1 - read, 2 - write */
1665 static bool
1666 cifs_find_fid_lock_conflict(struct cifs_fid_locks *fdlocks, __u64 offset,
1667 			    __u64 length, __u8 type, __u16 flags,
1668 			    struct cifsFileInfo *cfile,
1669 			    struct cifsLockInfo **conf_lock, int rw_check)
1670 {
1671 	struct cifsLockInfo *li;
1672 	struct cifsFileInfo *cur_cfile = fdlocks->cfile;
1673 	struct TCP_Server_Info *server = tlink_tcon(cfile->tlink)->ses->server;
1674 
1675 	list_for_each_entry(li, &fdlocks->locks, llist) {
1676 		if (offset + length <= li->offset ||
1677 		    offset >= li->offset + li->length)
1678 			continue;
1679 		if (rw_check != CIFS_LOCK_OP && current->tgid == li->pid &&
1680 		    server->ops->compare_fids(cfile, cur_cfile)) {
1681 			/* shared lock prevents write op through the same fid */
1682 			if (!(li->type & server->vals->shared_lock_type) ||
1683 			    rw_check != CIFS_WRITE_OP)
1684 				continue;
1685 		}
1686 		if ((type & server->vals->shared_lock_type) &&
1687 		    ((server->ops->compare_fids(cfile, cur_cfile) &&
1688 		     current->tgid == li->pid) || type == li->type))
1689 			continue;
1690 		if (rw_check == CIFS_LOCK_OP &&
1691 		    (flags & FL_OFDLCK) && (li->flags & FL_OFDLCK) &&
1692 		    server->ops->compare_fids(cfile, cur_cfile))
1693 			continue;
1694 		if (conf_lock)
1695 			*conf_lock = li;
1696 		trace_smb3_lock_conflict(cfile->fid.persistent_fid,
1697 					 offset, length, type,
1698 					 li->offset, li->length, li->type, li->pid);
1699 		return true;
1700 	}
1701 	return false;
1702 }
1703 
1704 bool
1705 cifs_find_lock_conflict(struct cifsFileInfo *cfile, __u64 offset, __u64 length,
1706 			__u8 type, __u16 flags,
1707 			struct cifsLockInfo **conf_lock, int rw_check)
1708 {
1709 	bool rc = false;
1710 	struct cifs_fid_locks *cur;
1711 	struct cifsInodeInfo *cinode = CIFS_I(d_inode(cfile->dentry));
1712 
1713 	list_for_each_entry(cur, &cinode->llist, llist) {
1714 		rc = cifs_find_fid_lock_conflict(cur, offset, length, type,
1715 						 flags, cfile, conf_lock,
1716 						 rw_check);
1717 		if (rc)
1718 			break;
1719 	}
1720 
1721 	return rc;
1722 }
1723 
1724 /*
1725  * Check if there is another lock that prevents us to set the lock (mandatory
1726  * style). If such a lock exists, update the flock structure with its
1727  * properties. Otherwise, set the flock type to F_UNLCK if we can cache brlocks
1728  * or leave it the same if we can't. Returns 0 if we don't need to request to
1729  * the server or 1 otherwise.
1730  */
1731 static int
1732 cifs_lock_test(struct cifsFileInfo *cfile, __u64 offset, __u64 length,
1733 	       __u8 type, struct file_lock *flock)
1734 {
1735 	int rc = 0;
1736 	struct cifsLockInfo *conf_lock;
1737 	struct cifsInodeInfo *cinode = CIFS_I(d_inode(cfile->dentry));
1738 	struct TCP_Server_Info *server = tlink_tcon(cfile->tlink)->ses->server;
1739 	bool exist;
1740 
1741 	down_read(&cinode->lock_sem);
1742 
1743 	exist = cifs_find_lock_conflict(cfile, offset, length, type,
1744 					flock->c.flc_flags, &conf_lock,
1745 					CIFS_LOCK_OP);
1746 	if (exist) {
1747 		flock->fl_start = conf_lock->offset;
1748 		flock->fl_end = conf_lock->offset + conf_lock->length - 1;
1749 		flock->c.flc_pid = conf_lock->pid;
1750 		if (conf_lock->type & server->vals->shared_lock_type)
1751 			flock->c.flc_type = F_RDLCK;
1752 		else
1753 			flock->c.flc_type = F_WRLCK;
1754 	} else if (!cinode->can_cache_brlcks)
1755 		rc = 1;
1756 	else
1757 		flock->c.flc_type = F_UNLCK;
1758 
1759 	up_read(&cinode->lock_sem);
1760 	return rc;
1761 }
1762 
1763 static void
1764 cifs_lock_add(struct cifsFileInfo *cfile, struct cifsLockInfo *lock)
1765 {
1766 	struct cifsInodeInfo *cinode = CIFS_I(d_inode(cfile->dentry));
1767 	cifs_down_write(&cinode->lock_sem);
1768 	list_add_tail(&lock->llist, &cfile->llist->locks);
1769 	up_write(&cinode->lock_sem);
1770 }
1771 
1772 /*
1773  * Set the byte-range lock (mandatory style). Returns:
1774  * 1) 0, if we set the lock and don't need to request to the server;
1775  * 2) 1, if no locks prevent us but we need to request to the server;
1776  * 3) -EACCES, if there is a lock that prevents us and wait is false.
1777  */
1778 static int
1779 cifs_lock_add_if(struct cifsFileInfo *cfile, struct cifsLockInfo *lock,
1780 		 bool wait, unsigned int xid)
1781 {
1782 	struct cifsLockInfo *conf_lock;
1783 	struct cifsInodeInfo *cinode = CIFS_I(d_inode(cfile->dentry));
1784 	bool exist;
1785 	int rc = 0;
1786 
1787 try_again:
1788 	exist = false;
1789 	cifs_down_write(&cinode->lock_sem);
1790 
1791 	exist = cifs_find_lock_conflict(cfile, lock->offset, lock->length,
1792 					lock->type, lock->flags, &conf_lock,
1793 					CIFS_LOCK_OP);
1794 	if (!exist && cinode->can_cache_brlcks) {
1795 		struct cifs_tcon *tcon = tlink_tcon(cfile->tlink);
1796 
1797 		list_add_tail(&lock->llist, &cfile->llist->locks);
1798 		trace_smb3_lock_cached(xid, cfile->fid.persistent_fid,
1799 				       tcon->tid, tcon->ses->Suid,
1800 				       lock->offset, lock->length,
1801 				       lock->type, 1, 0);
1802 		up_write(&cinode->lock_sem);
1803 		return rc;
1804 	}
1805 
1806 	if (!exist)
1807 		rc = 1;
1808 	else if (!wait)
1809 		rc = -EACCES;
1810 	else {
1811 		list_add_tail(&lock->blist, &conf_lock->blist);
1812 		up_write(&cinode->lock_sem);
1813 		rc = wait_event_interruptible(lock->block_q,
1814 					(lock->blist.prev == &lock->blist) &&
1815 					(lock->blist.next == &lock->blist));
1816 		if (!rc)
1817 			goto try_again;
1818 		cifs_down_write(&cinode->lock_sem);
1819 		list_del_init(&lock->blist);
1820 	}
1821 
1822 	up_write(&cinode->lock_sem);
1823 	return rc;
1824 }
1825 
1826 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
1827 /*
1828  * Check if there is another lock that prevents us to set the lock (posix
1829  * style). If such a lock exists, update the flock structure with its
1830  * properties. Otherwise, set the flock type to F_UNLCK if we can cache brlocks
1831  * or leave it the same if we can't. Returns 0 if we don't need to request to
1832  * the server or 1 otherwise.
1833  */
1834 static int
1835 cifs_posix_lock_test(struct file *file, struct file_lock *flock)
1836 {
1837 	int rc = 0;
1838 	struct cifsInodeInfo *cinode = CIFS_I(file_inode(file));
1839 	unsigned char saved_type = flock->c.flc_type;
1840 
1841 	if ((flock->c.flc_flags & FL_POSIX) == 0)
1842 		return 1;
1843 
1844 	down_read(&cinode->lock_sem);
1845 	posix_test_lock(file, flock);
1846 
1847 	if (lock_is_unlock(flock) && !cinode->can_cache_brlcks) {
1848 		flock->c.flc_type = saved_type;
1849 		rc = 1;
1850 	}
1851 
1852 	up_read(&cinode->lock_sem);
1853 	return rc;
1854 }
1855 
1856 /*
1857  * Set the byte-range lock (posix style). Returns:
1858  * 1) <0, if the error occurs while setting the lock;
1859  * 2) 0, if we set the lock and don't need to request to the server;
1860  * 3) FILE_LOCK_DEFERRED, if we will wait for some other file_lock;
1861  * 4) FILE_LOCK_DEFERRED + 1, if we need to request to the server.
1862  */
1863 static int
1864 cifs_posix_lock_set(struct file *file, struct file_lock *flock)
1865 {
1866 	struct cifsInodeInfo *cinode = CIFS_I(file_inode(file));
1867 	int rc = FILE_LOCK_DEFERRED + 1;
1868 
1869 	if ((flock->c.flc_flags & FL_POSIX) == 0)
1870 		return rc;
1871 
1872 	cifs_down_write(&cinode->lock_sem);
1873 	if (!cinode->can_cache_brlcks) {
1874 		up_write(&cinode->lock_sem);
1875 		return rc;
1876 	}
1877 
1878 	rc = posix_lock_file(file, flock, NULL);
1879 	up_write(&cinode->lock_sem);
1880 	return rc;
1881 }
1882 
1883 int
1884 cifs_push_mandatory_locks(struct cifsFileInfo *cfile)
1885 {
1886 	unsigned int xid;
1887 	int rc = 0, stored_rc;
1888 	struct cifsLockInfo *li, *tmp;
1889 	struct cifs_tcon *tcon;
1890 	unsigned int num, max_num, max_buf;
1891 	LOCKING_ANDX_RANGE *buf, *cur;
1892 	static const int types[] = {
1893 		LOCKING_ANDX_LARGE_FILES,
1894 		LOCKING_ANDX_SHARED_LOCK | LOCKING_ANDX_LARGE_FILES
1895 	};
1896 	int i;
1897 
1898 	xid = get_xid();
1899 	tcon = tlink_tcon(cfile->tlink);
1900 
1901 	/*
1902 	 * Accessing maxBuf is racy with cifs_reconnect - need to store value
1903 	 * and check it before using.
1904 	 */
1905 	max_buf = tcon->ses->server->maxBuf;
1906 	if (max_buf < (sizeof(struct smb_hdr) + sizeof(LOCKING_ANDX_RANGE))) {
1907 		free_xid(xid);
1908 		return -EINVAL;
1909 	}
1910 
1911 	BUILD_BUG_ON(sizeof(struct smb_hdr) + sizeof(LOCKING_ANDX_RANGE) >
1912 		     PAGE_SIZE);
1913 	max_buf = min_t(unsigned int, max_buf - sizeof(struct smb_hdr),
1914 			PAGE_SIZE);
1915 	max_num = (max_buf - sizeof(struct smb_hdr)) /
1916 						sizeof(LOCKING_ANDX_RANGE);
1917 	buf = kzalloc_objs(LOCKING_ANDX_RANGE, max_num);
1918 	if (!buf) {
1919 		free_xid(xid);
1920 		return -ENOMEM;
1921 	}
1922 
1923 	for (i = 0; i < 2; i++) {
1924 		cur = buf;
1925 		num = 0;
1926 		list_for_each_entry_safe(li, tmp, &cfile->llist->locks, llist) {
1927 			if (li->type != types[i])
1928 				continue;
1929 			cur->Pid = cpu_to_le16(li->pid);
1930 			cur->LengthLow = cpu_to_le32((u32)li->length);
1931 			cur->LengthHigh = cpu_to_le32((u32)(li->length>>32));
1932 			cur->OffsetLow = cpu_to_le32((u32)li->offset);
1933 			cur->OffsetHigh = cpu_to_le32((u32)(li->offset>>32));
1934 			if (++num == max_num) {
1935 				stored_rc = cifs_lockv(xid, tcon,
1936 						       cfile->fid.netfid,
1937 						       (__u8)li->type, 0, num,
1938 						       buf);
1939 				if (stored_rc)
1940 					rc = stored_rc;
1941 				cur = buf;
1942 				num = 0;
1943 			} else
1944 				cur++;
1945 		}
1946 
1947 		if (num) {
1948 			stored_rc = cifs_lockv(xid, tcon, cfile->fid.netfid,
1949 					       (__u8)types[i], 0, num, buf);
1950 			if (stored_rc)
1951 				rc = stored_rc;
1952 		}
1953 	}
1954 
1955 	kfree(buf);
1956 	free_xid(xid);
1957 	return rc;
1958 }
1959 
1960 static __u32
1961 hash_lockowner(fl_owner_t owner)
1962 {
1963 	return cifs_lock_secret ^ hash32_ptr((const void *)owner);
1964 }
1965 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
1966 
1967 struct lock_to_push {
1968 	struct list_head llist;
1969 	__u64 offset;
1970 	__u64 length;
1971 	__u32 pid;
1972 	__u16 netfid;
1973 	__u8 type;
1974 };
1975 
1976 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
1977 static int
1978 cifs_push_posix_locks(struct cifsFileInfo *cfile)
1979 {
1980 	struct inode *inode = d_inode(cfile->dentry);
1981 	struct cifs_tcon *tcon = tlink_tcon(cfile->tlink);
1982 	struct file_lock *flock;
1983 	struct file_lock_context *flctx = locks_inode_context(inode);
1984 	unsigned int count = 0, i;
1985 	int rc = 0, xid, type;
1986 	struct list_head locks_to_send, *el;
1987 	struct lock_to_push *lck, *tmp;
1988 	__u64 length;
1989 
1990 	xid = get_xid();
1991 
1992 	if (!flctx)
1993 		goto out;
1994 
1995 	spin_lock(&flctx->flc_lock);
1996 	list_for_each(el, &flctx->flc_posix) {
1997 		count++;
1998 	}
1999 	spin_unlock(&flctx->flc_lock);
2000 
2001 	INIT_LIST_HEAD(&locks_to_send);
2002 
2003 	/*
2004 	 * Allocating count locks is enough because no FL_POSIX locks can be
2005 	 * added to the list while we are holding cinode->lock_sem that
2006 	 * protects locking operations of this inode.
2007 	 */
2008 	for (i = 0; i < count; i++) {
2009 		lck = kmalloc_obj(struct lock_to_push);
2010 		if (!lck) {
2011 			rc = -ENOMEM;
2012 			goto err_out;
2013 		}
2014 		list_add_tail(&lck->llist, &locks_to_send);
2015 	}
2016 
2017 	el = locks_to_send.next;
2018 	spin_lock(&flctx->flc_lock);
2019 	for_each_file_lock(flock, &flctx->flc_posix) {
2020 		unsigned char ftype = flock->c.flc_type;
2021 
2022 		if (el == &locks_to_send) {
2023 			/*
2024 			 * The list ended. We don't have enough allocated
2025 			 * structures - something is really wrong.
2026 			 */
2027 			cifs_dbg(VFS, "Can't push all brlocks!\n");
2028 			break;
2029 		}
2030 		length = cifs_flock_len(flock);
2031 		if (ftype == F_RDLCK || ftype == F_SHLCK)
2032 			type = CIFS_RDLCK;
2033 		else
2034 			type = CIFS_WRLCK;
2035 		lck = list_entry(el, struct lock_to_push, llist);
2036 		lck->pid = hash_lockowner(flock->c.flc_owner);
2037 		lck->netfid = cfile->fid.netfid;
2038 		lck->length = length;
2039 		lck->type = type;
2040 		lck->offset = flock->fl_start;
2041 	}
2042 	spin_unlock(&flctx->flc_lock);
2043 
2044 	list_for_each_entry_safe(lck, tmp, &locks_to_send, llist) {
2045 		int stored_rc;
2046 
2047 		stored_rc = CIFSSMBPosixLock(xid, tcon, lck->netfid, lck->pid,
2048 					     lck->offset, lck->length, NULL,
2049 					     lck->type, 0);
2050 		if (stored_rc)
2051 			rc = stored_rc;
2052 		list_del(&lck->llist);
2053 		kfree(lck);
2054 	}
2055 
2056 out:
2057 	free_xid(xid);
2058 	return rc;
2059 err_out:
2060 	list_for_each_entry_safe(lck, tmp, &locks_to_send, llist) {
2061 		list_del(&lck->llist);
2062 		kfree(lck);
2063 	}
2064 	goto out;
2065 }
2066 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
2067 
2068 static int
2069 cifs_push_locks(struct cifsFileInfo *cfile)
2070 {
2071 	struct cifsInodeInfo *cinode = CIFS_I(d_inode(cfile->dentry));
2072 	struct cifs_tcon *tcon = tlink_tcon(cfile->tlink);
2073 	int rc = 0;
2074 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
2075 	struct cifs_sb_info *cifs_sb = CIFS_SB(cinode);
2076 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
2077 
2078 	/* we are going to update can_cache_brlcks here - need a write access */
2079 	cifs_down_write(&cinode->lock_sem);
2080 	if (!cinode->can_cache_brlcks) {
2081 		up_write(&cinode->lock_sem);
2082 		return rc;
2083 	}
2084 
2085 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
2086 	if (cap_unix(tcon->ses) &&
2087 	    (CIFS_UNIX_FCNTL_CAP & le64_to_cpu(tcon->fsUnixInfo.Capability)) &&
2088 	    ((cifs_sb_flags(cifs_sb) & CIFS_MOUNT_NOPOSIXBRL) == 0))
2089 		rc = cifs_push_posix_locks(cfile);
2090 	else
2091 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
2092 		rc = tcon->ses->server->ops->push_mand_locks(cfile);
2093 
2094 	cinode->can_cache_brlcks = false;
2095 	up_write(&cinode->lock_sem);
2096 	return rc;
2097 }
2098 
2099 static void
2100 cifs_read_flock(struct file_lock *flock, __u32 *type, int *lock, int *unlock,
2101 		bool *wait_flag, struct TCP_Server_Info *server)
2102 {
2103 	if (flock->c.flc_flags & FL_POSIX)
2104 		cifs_dbg(FYI, "Posix\n");
2105 	if (flock->c.flc_flags & FL_FLOCK)
2106 		cifs_dbg(FYI, "Flock\n");
2107 	if (flock->c.flc_flags & FL_SLEEP) {
2108 		cifs_dbg(FYI, "Blocking lock\n");
2109 		*wait_flag = true;
2110 	}
2111 	if (flock->c.flc_flags & FL_ACCESS)
2112 		cifs_dbg(FYI, "Process suspended by mandatory locking - not implemented yet\n");
2113 	if (flock->c.flc_flags & FL_LEASE)
2114 		cifs_dbg(FYI, "Lease on file - not implemented yet\n");
2115 	if (flock->c.flc_flags &
2116 	    (~(FL_POSIX | FL_FLOCK | FL_SLEEP |
2117 	       FL_ACCESS | FL_LEASE | FL_CLOSE | FL_OFDLCK)))
2118 		cifs_dbg(FYI, "Unknown lock flags 0x%x\n",
2119 		         flock->c.flc_flags);
2120 
2121 	*type = server->vals->large_lock_type;
2122 	if (lock_is_write(flock)) {
2123 		cifs_dbg(FYI, "F_WRLCK\n");
2124 		*type |= server->vals->exclusive_lock_type;
2125 		*lock = 1;
2126 	} else if (lock_is_unlock(flock)) {
2127 		cifs_dbg(FYI, "F_UNLCK\n");
2128 		*type |= server->vals->unlock_lock_type;
2129 		*unlock = 1;
2130 		/* Check if unlock includes more than one lock range */
2131 	} else if (lock_is_read(flock)) {
2132 		cifs_dbg(FYI, "F_RDLCK\n");
2133 		*type |= server->vals->shared_lock_type;
2134 		*lock = 1;
2135 	} else if (flock->c.flc_type == F_EXLCK) {
2136 		cifs_dbg(FYI, "F_EXLCK\n");
2137 		*type |= server->vals->exclusive_lock_type;
2138 		*lock = 1;
2139 	} else if (flock->c.flc_type == F_SHLCK) {
2140 		cifs_dbg(FYI, "F_SHLCK\n");
2141 		*type |= server->vals->shared_lock_type;
2142 		*lock = 1;
2143 	} else
2144 		cifs_dbg(FYI, "Unknown type of lock\n");
2145 }
2146 
2147 static int
2148 cifs_getlk(struct file *file, struct file_lock *flock, __u32 type,
2149 	   bool wait_flag, bool posix_lck, unsigned int xid)
2150 {
2151 	int rc = 0;
2152 	__u64 length = cifs_flock_len(flock);
2153 	struct cifsFileInfo *cfile = (struct cifsFileInfo *)file->private_data;
2154 	struct cifs_tcon *tcon = tlink_tcon(cfile->tlink);
2155 	struct TCP_Server_Info *server = tcon->ses->server;
2156 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
2157 	__u16 netfid = cfile->fid.netfid;
2158 
2159 	if (posix_lck) {
2160 		int posix_lock_type;
2161 
2162 		rc = cifs_posix_lock_test(file, flock);
2163 		if (!rc)
2164 			return rc;
2165 
2166 		if (type & server->vals->shared_lock_type)
2167 			posix_lock_type = CIFS_RDLCK;
2168 		else
2169 			posix_lock_type = CIFS_WRLCK;
2170 		rc = CIFSSMBPosixLock(xid, tcon, netfid,
2171 				      hash_lockowner(flock->c.flc_owner),
2172 				      flock->fl_start, length, flock,
2173 				      posix_lock_type, wait_flag);
2174 		return rc;
2175 	}
2176 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
2177 
2178 	rc = cifs_lock_test(cfile, flock->fl_start, length, type, flock);
2179 	if (!rc)
2180 		return rc;
2181 
2182 	/* BB we could chain these into one lock request BB */
2183 	rc = server->ops->mand_lock(xid, cfile, flock->fl_start, length, type,
2184 				    1, 0, false);
2185 	if (rc == 0) {
2186 		rc = server->ops->mand_lock(xid, cfile, flock->fl_start, length,
2187 					    type, 0, 1, false);
2188 		flock->c.flc_type = F_UNLCK;
2189 		if (rc != 0)
2190 			cifs_dbg(VFS, "Error unlocking previously locked range %d during test of lock\n",
2191 				 rc);
2192 		return 0;
2193 	}
2194 
2195 	if (type & server->vals->shared_lock_type) {
2196 		flock->c.flc_type = F_WRLCK;
2197 		return 0;
2198 	}
2199 
2200 	type &= ~server->vals->exclusive_lock_type;
2201 
2202 	rc = server->ops->mand_lock(xid, cfile, flock->fl_start, length,
2203 				    type | server->vals->shared_lock_type,
2204 				    1, 0, false);
2205 	if (rc == 0) {
2206 		rc = server->ops->mand_lock(xid, cfile, flock->fl_start, length,
2207 			type | server->vals->shared_lock_type, 0, 1, false);
2208 		flock->c.flc_type = F_RDLCK;
2209 		if (rc != 0)
2210 			cifs_dbg(VFS, "Error unlocking previously locked range %d during test of lock\n",
2211 				 rc);
2212 	} else
2213 		flock->c.flc_type = F_WRLCK;
2214 
2215 	return 0;
2216 }
2217 
2218 void
2219 cifs_move_llist(struct list_head *source, struct list_head *dest)
2220 {
2221 	struct list_head *li, *tmp;
2222 	list_for_each_safe(li, tmp, source)
2223 		list_move(li, dest);
2224 }
2225 
2226 int
2227 cifs_get_hardlink_path(struct cifs_tcon *tcon, struct inode *inode,
2228 				struct file *file)
2229 {
2230 	struct cifsFileInfo *open_file = NULL;
2231 	struct cifsInodeInfo *cinode = CIFS_I(inode);
2232 	int rc = 0;
2233 
2234 	spin_lock(&tcon->open_file_lock);
2235 	spin_lock(&cinode->open_file_lock);
2236 
2237 	list_for_each_entry(open_file, &cinode->openFileList, flist) {
2238 		if (file->f_flags == open_file->f_flags) {
2239 			rc = -EINVAL;
2240 			break;
2241 		}
2242 	}
2243 
2244 	spin_unlock(&cinode->open_file_lock);
2245 	spin_unlock(&tcon->open_file_lock);
2246 	return rc;
2247 }
2248 
2249 void
2250 cifs_free_llist(struct list_head *llist)
2251 {
2252 	struct cifsLockInfo *li, *tmp;
2253 	list_for_each_entry_safe(li, tmp, llist, llist) {
2254 		cifs_del_lock_waiters(li);
2255 		list_del(&li->llist);
2256 		kfree(li);
2257 	}
2258 }
2259 
2260 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
2261 int
2262 cifs_unlock_range(struct cifsFileInfo *cfile, struct file_lock *flock,
2263 		  unsigned int xid)
2264 {
2265 	int rc = 0, stored_rc;
2266 	static const int types[] = {
2267 		LOCKING_ANDX_LARGE_FILES,
2268 		LOCKING_ANDX_SHARED_LOCK | LOCKING_ANDX_LARGE_FILES
2269 	};
2270 	unsigned int i;
2271 	unsigned int max_num, num, max_buf;
2272 	LOCKING_ANDX_RANGE *buf, *cur;
2273 	struct cifs_tcon *tcon = tlink_tcon(cfile->tlink);
2274 	struct cifsInodeInfo *cinode = CIFS_I(d_inode(cfile->dentry));
2275 	struct cifsLockInfo *li, *tmp;
2276 	__u64 length = cifs_flock_len(flock);
2277 	LIST_HEAD(tmp_llist);
2278 
2279 	/*
2280 	 * Accessing maxBuf is racy with cifs_reconnect - need to store value
2281 	 * and check it before using.
2282 	 */
2283 	max_buf = tcon->ses->server->maxBuf;
2284 	if (max_buf < (sizeof(struct smb_hdr) + sizeof(LOCKING_ANDX_RANGE)))
2285 		return -EINVAL;
2286 
2287 	BUILD_BUG_ON(sizeof(struct smb_hdr) + sizeof(LOCKING_ANDX_RANGE) >
2288 		     PAGE_SIZE);
2289 	max_buf = min_t(unsigned int, max_buf - sizeof(struct smb_hdr),
2290 			PAGE_SIZE);
2291 	max_num = (max_buf - sizeof(struct smb_hdr)) /
2292 						sizeof(LOCKING_ANDX_RANGE);
2293 	buf = kzalloc_objs(LOCKING_ANDX_RANGE, max_num);
2294 	if (!buf)
2295 		return -ENOMEM;
2296 
2297 	cifs_down_write(&cinode->lock_sem);
2298 	for (i = 0; i < 2; i++) {
2299 		cur = buf;
2300 		num = 0;
2301 		list_for_each_entry_safe(li, tmp, &cfile->llist->locks, llist) {
2302 			if (flock->fl_start > li->offset ||
2303 			    (flock->fl_start + length) <
2304 			    (li->offset + li->length))
2305 				continue;
2306 			if (current->tgid != li->pid)
2307 				continue;
2308 			if (types[i] != li->type)
2309 				continue;
2310 			if (cinode->can_cache_brlcks) {
2311 				/*
2312 				 * We can cache brlock requests - simply remove
2313 				 * a lock from the file's list.
2314 				 */
2315 				list_del(&li->llist);
2316 				cifs_del_lock_waiters(li);
2317 				kfree(li);
2318 				continue;
2319 			}
2320 			cur->Pid = cpu_to_le16(li->pid);
2321 			cur->LengthLow = cpu_to_le32((u32)li->length);
2322 			cur->LengthHigh = cpu_to_le32((u32)(li->length>>32));
2323 			cur->OffsetLow = cpu_to_le32((u32)li->offset);
2324 			cur->OffsetHigh = cpu_to_le32((u32)(li->offset>>32));
2325 			/*
2326 			 * We need to save a lock here to let us add it again to
2327 			 * the file's list if the unlock range request fails on
2328 			 * the server.
2329 			 */
2330 			list_move(&li->llist, &tmp_llist);
2331 			if (++num == max_num) {
2332 				stored_rc = cifs_lockv(xid, tcon,
2333 						       cfile->fid.netfid,
2334 						       li->type, num, 0, buf);
2335 				if (stored_rc) {
2336 					/*
2337 					 * We failed on the unlock range
2338 					 * request - add all locks from the tmp
2339 					 * list to the head of the file's list.
2340 					 */
2341 					cifs_move_llist(&tmp_llist,
2342 							&cfile->llist->locks);
2343 					rc = stored_rc;
2344 				} else
2345 					/*
2346 					 * The unlock range request succeed -
2347 					 * free the tmp list.
2348 					 */
2349 					cifs_free_llist(&tmp_llist);
2350 				cur = buf;
2351 				num = 0;
2352 			} else
2353 				cur++;
2354 		}
2355 		if (num) {
2356 			stored_rc = cifs_lockv(xid, tcon, cfile->fid.netfid,
2357 					       types[i], num, 0, buf);
2358 			if (stored_rc) {
2359 				cifs_move_llist(&tmp_llist,
2360 						&cfile->llist->locks);
2361 				rc = stored_rc;
2362 			} else
2363 				cifs_free_llist(&tmp_llist);
2364 		}
2365 	}
2366 
2367 	up_write(&cinode->lock_sem);
2368 	kfree(buf);
2369 	return rc;
2370 }
2371 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
2372 
2373 static int
2374 cifs_setlk(struct file *file, struct file_lock *flock, __u32 type,
2375 	   bool wait_flag, bool posix_lck, int lock, int unlock,
2376 	   unsigned int xid)
2377 {
2378 	int rc = 0;
2379 	__u64 length = cifs_flock_len(flock);
2380 	struct cifsFileInfo *cfile = (struct cifsFileInfo *)file->private_data;
2381 	struct cifs_tcon *tcon = tlink_tcon(cfile->tlink);
2382 	struct TCP_Server_Info *server = tcon->ses->server;
2383 	struct inode *inode = d_inode(cfile->dentry);
2384 
2385 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
2386 	if (posix_lck) {
2387 		int posix_lock_type;
2388 
2389 		rc = cifs_posix_lock_set(file, flock);
2390 		if (rc <= FILE_LOCK_DEFERRED)
2391 			return rc;
2392 
2393 		if (type & server->vals->shared_lock_type)
2394 			posix_lock_type = CIFS_RDLCK;
2395 		else
2396 			posix_lock_type = CIFS_WRLCK;
2397 
2398 		if (unlock == 1)
2399 			posix_lock_type = CIFS_UNLCK;
2400 
2401 		rc = CIFSSMBPosixLock(xid, tcon, cfile->fid.netfid,
2402 				      hash_lockowner(flock->c.flc_owner),
2403 				      flock->fl_start, length,
2404 				      NULL, posix_lock_type, wait_flag);
2405 		goto out;
2406 	}
2407 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
2408 	if (lock) {
2409 		struct cifsLockInfo *lock;
2410 
2411 		lock = cifs_lock_init(flock->fl_start, length, type,
2412 				      flock->c.flc_flags);
2413 		if (!lock)
2414 			return -ENOMEM;
2415 
2416 		rc = cifs_lock_add_if(cfile, lock, wait_flag, xid);
2417 		if (rc < 0) {
2418 			kfree(lock);
2419 			return rc;
2420 		}
2421 		if (!rc)
2422 			goto out;
2423 
2424 		/*
2425 		 * Windows 7 server can delay breaking lease from read to None
2426 		 * if we set a byte-range lock on a file - break it explicitly
2427 		 * before sending the lock to the server to be sure the next
2428 		 * read won't conflict with non-overlapted locks due to
2429 		 * pagereading.
2430 		 */
2431 		if (!CIFS_CACHE_WRITE(CIFS_I(inode)) &&
2432 					CIFS_CACHE_READ(CIFS_I(inode))) {
2433 			cifs_zap_mapping(inode);
2434 			cifs_dbg(FYI, "Set no oplock for inode=%p due to mand locks\n",
2435 				 inode);
2436 			cifs_reset_oplock(CIFS_I(inode));
2437 		}
2438 
2439 		rc = server->ops->mand_lock(xid, cfile, flock->fl_start, length,
2440 					    type, 1, 0, wait_flag);
2441 		if (rc) {
2442 			kfree(lock);
2443 			return rc;
2444 		}
2445 
2446 		cifs_lock_add(cfile, lock);
2447 	} else if (unlock)
2448 		rc = server->ops->mand_unlock_range(cfile, flock, xid);
2449 
2450 out:
2451 	if ((flock->c.flc_flags & FL_POSIX) || (flock->c.flc_flags & FL_FLOCK)) {
2452 		/*
2453 		 * If this is a request to remove all locks because we
2454 		 * are closing the file, it doesn't matter if the
2455 		 * unlocking failed as both cifs.ko and the SMB server
2456 		 * remove the lock on file close
2457 		 */
2458 		if (rc) {
2459 			cifs_dbg(VFS, "%s failed rc=%d\n", __func__, rc);
2460 			if (!(flock->c.flc_flags & FL_CLOSE))
2461 				return rc;
2462 		}
2463 		rc = locks_lock_file_wait(file, flock);
2464 	}
2465 	return rc;
2466 }
2467 
2468 int cifs_flock(struct file *file, int cmd, struct file_lock *fl)
2469 {
2470 	int rc, xid;
2471 	int lock = 0, unlock = 0;
2472 	bool wait_flag = false;
2473 	bool posix_lck = false;
2474 	struct cifs_sb_info *cifs_sb;
2475 	struct cifs_tcon *tcon;
2476 	struct cifsFileInfo *cfile;
2477 	__u32 type;
2478 
2479 	xid = get_xid();
2480 
2481 	if (!(fl->c.flc_flags & FL_FLOCK)) {
2482 		rc = -ENOLCK;
2483 		free_xid(xid);
2484 		return rc;
2485 	}
2486 
2487 	cfile = (struct cifsFileInfo *)file->private_data;
2488 	tcon = tlink_tcon(cfile->tlink);
2489 
2490 	cifs_read_flock(fl, &type, &lock, &unlock, &wait_flag,
2491 			tcon->ses->server);
2492 	cifs_sb = CIFS_SB(file);
2493 
2494 	if (cap_unix(tcon->ses) &&
2495 	    (CIFS_UNIX_FCNTL_CAP & le64_to_cpu(tcon->fsUnixInfo.Capability)) &&
2496 	    ((cifs_sb_flags(cifs_sb) & CIFS_MOUNT_NOPOSIXBRL) == 0))
2497 		posix_lck = true;
2498 
2499 	if (!lock && !unlock) {
2500 		/*
2501 		 * if no lock or unlock then nothing to do since we do not
2502 		 * know what it is
2503 		 */
2504 		rc = -EOPNOTSUPP;
2505 		free_xid(xid);
2506 		return rc;
2507 	}
2508 
2509 	rc = cifs_setlk(file, fl, type, wait_flag, posix_lck, lock, unlock,
2510 			xid);
2511 	free_xid(xid);
2512 	return rc;
2513 
2514 
2515 }
2516 
2517 int cifs_lock(struct file *file, int cmd, struct file_lock *flock)
2518 {
2519 	struct cifs_sb_info *cifs_sb = CIFS_SB(file);
2520 	struct cifsFileInfo *cfile;
2521 	int lock = 0, unlock = 0;
2522 	bool wait_flag = false;
2523 	bool posix_lck = false;
2524 	struct cifs_tcon *tcon;
2525 	__u32 type;
2526 	int rc, xid;
2527 
2528 	rc = -EACCES;
2529 	xid = get_xid();
2530 
2531 	cifs_dbg(FYI, "%s: %pD2 cmd=0x%x type=0x%x flags=0x%x r=%lld:%lld\n", __func__, file, cmd,
2532 		 flock->c.flc_flags, flock->c.flc_type,
2533 		 (long long)flock->fl_start,
2534 		 (long long)flock->fl_end);
2535 
2536 	cfile = (struct cifsFileInfo *)file->private_data;
2537 	tcon = tlink_tcon(cfile->tlink);
2538 
2539 	cifs_read_flock(flock, &type, &lock, &unlock, &wait_flag,
2540 			tcon->ses->server);
2541 	set_bit(CIFS_INO_CLOSE_ON_LOCK, &CIFS_I(d_inode(cfile->dentry))->flags);
2542 
2543 	if (cap_unix(tcon->ses) &&
2544 	    (CIFS_UNIX_FCNTL_CAP & le64_to_cpu(tcon->fsUnixInfo.Capability)) &&
2545 	    ((cifs_sb_flags(cifs_sb) & CIFS_MOUNT_NOPOSIXBRL) == 0))
2546 		posix_lck = true;
2547 	/*
2548 	 * BB add code here to normalize offset and length to account for
2549 	 * negative length which we can not accept over the wire.
2550 	 */
2551 	if (IS_GETLK(cmd)) {
2552 		rc = cifs_getlk(file, flock, type, wait_flag, posix_lck, xid);
2553 		free_xid(xid);
2554 		return rc;
2555 	}
2556 
2557 	if (!lock && !unlock) {
2558 		/*
2559 		 * if no lock or unlock then nothing to do since we do not
2560 		 * know what it is
2561 		 */
2562 		free_xid(xid);
2563 		return -EOPNOTSUPP;
2564 	}
2565 
2566 	rc = cifs_setlk(file, flock, type, wait_flag, posix_lck, lock, unlock,
2567 			xid);
2568 	free_xid(xid);
2569 	return rc;
2570 }
2571 
2572 static void cifs_update_i_blocks_for_write(struct inode *inode, loff_t start,
2573 					     loff_t end)
2574 {
2575 	struct cifsInodeInfo *cinode = CIFS_I(inode);
2576 	u64 allocated_end = CIFS_INO_BYTES(inode->i_blocks);
2577 	u64 blocks;
2578 
2579 	if (cinode->cifsAttrs & FILE_ATTRIBUTE_SPARSE_FILE)
2580 		return;
2581 
2582 	/*
2583 	 * Grow the local estimate only across the currently known allocated
2584 	 * prefix. A write beyond that may leave a hole.
2585 	 */
2586 	if ((u64)start > allocated_end)
2587 		return;
2588 
2589 	blocks = CIFS_INO_BLOCKS(end);
2590 	if ((u64)inode->i_blocks < blocks)
2591 		inode->i_blocks = blocks;
2592 }
2593 
2594 static void cifs_update_i_blocks_after_write(struct kiocb *iocb,
2595 						ssize_t written)
2596 {
2597 	struct inode *inode = file_inode(iocb->ki_filp);
2598 	loff_t end = iocb->ki_pos;
2599 
2600 	if (written <= 0)
2601 		return;
2602 
2603 	spin_lock(&inode->i_lock);
2604 	cifs_update_i_blocks_for_write(inode, end - written, end);
2605 	spin_unlock(&inode->i_lock);
2606 }
2607 
2608 void cifs_write_subrequest_terminated(struct cifs_io_subrequest *wdata, ssize_t result)
2609 {
2610 	struct netfs_io_request *wreq = wdata->rreq;
2611 	struct inode *inode = wreq->inode;
2612 	struct netfs_inode *ictx = netfs_inode(inode);
2613 	loff_t wrend;
2614 
2615 	if (result > 0) {
2616 		spin_lock(&inode->i_lock);
2617 
2618 		wrend = wdata->subreq.start + wdata->subreq.transferred + result;
2619 
2620 		if (wrend > ictx->_zero_point &&
2621 		    (wdata->rreq->origin == NETFS_UNBUFFERED_WRITE ||
2622 		     wdata->rreq->origin == NETFS_DIO_WRITE))
2623 			netfs_write_zero_point(inode, wrend);
2624 		if (wrend > ictx->_remote_i_size)
2625 			netfs_resize_file(ictx, wrend, true);
2626 		cifs_update_i_blocks_for_write(inode, wdata->subreq.start,
2627 						 wrend);
2628 
2629 		spin_unlock(&inode->i_lock);
2630 	}
2631 
2632 	netfs_write_subrequest_terminated(&wdata->subreq, result);
2633 }
2634 
2635 static bool open_flags_match(struct cifsInodeInfo *cinode,
2636 			     unsigned int oflags, unsigned int cflags)
2637 {
2638 	struct inode *inode = &cinode->netfs.inode;
2639 	int crw = 0, orw = 0;
2640 
2641 	oflags &= ~(O_CREAT | O_EXCL | O_TRUNC);
2642 	cflags &= ~(O_CREAT | O_EXCL | O_TRUNC);
2643 
2644 	if (cifs_fscache_enabled(inode)) {
2645 		if (OPEN_FMODE(cflags) & FMODE_WRITE)
2646 			crw = 1;
2647 		if (OPEN_FMODE(oflags) & FMODE_WRITE)
2648 			orw = 1;
2649 	}
2650 	if (cifs_convert_flags(oflags, orw) != cifs_convert_flags(cflags, crw))
2651 		return false;
2652 
2653 	return (oflags & (O_SYNC | O_DIRECT)) == (cflags & (O_SYNC | O_DIRECT));
2654 }
2655 
2656 struct cifsFileInfo *__find_readable_file(struct cifsInodeInfo *cifs_inode,
2657 					  unsigned int find_flags,
2658 					  unsigned int open_flags)
2659 {
2660 	struct cifs_sb_info *cifs_sb = CIFS_SB(cifs_inode);
2661 	bool fsuid_only = find_flags & FIND_FSUID_ONLY;
2662 	struct cifsFileInfo *open_file = NULL;
2663 
2664 	/* only filter by fsuid on multiuser mounts */
2665 	if (!(cifs_sb_flags(cifs_sb) & CIFS_MOUNT_MULTIUSER))
2666 		fsuid_only = false;
2667 
2668 	spin_lock(&cifs_inode->open_file_lock);
2669 	/* we could simply get the first_list_entry since write-only entries
2670 	   are always at the end of the list but since the first entry might
2671 	   have a close pending, we go through the whole list */
2672 	list_for_each_entry(open_file, &cifs_inode->openFileList, flist) {
2673 		if (fsuid_only && !uid_eq(open_file->uid, current_fsuid()))
2674 			continue;
2675 		if ((find_flags & FIND_NO_PENDING_DELETE) &&
2676 		    open_file->status_file_deleted)
2677 			continue;
2678 		if ((find_flags & FIND_OPEN_FLAGS) &&
2679 		    !open_flags_match(cifs_inode, open_flags,
2680 				      open_file->f_flags))
2681 			continue;
2682 		if (OPEN_FMODE(open_file->f_flags) & FMODE_READ) {
2683 			if ((!open_file->invalidHandle)) {
2684 				/* found a good file */
2685 				/* lock it so it will not be closed on us */
2686 				cifsFileInfo_get(open_file);
2687 				spin_unlock(&cifs_inode->open_file_lock);
2688 				return open_file;
2689 			} /* else might as well continue, and look for
2690 			     another, or simply have the caller reopen it
2691 			     again rather than trying to fix this handle */
2692 		} else /* write only file */
2693 			break; /* write only files are last so must be done */
2694 	}
2695 	spin_unlock(&cifs_inode->open_file_lock);
2696 	return NULL;
2697 }
2698 
2699 /* Return -EBADF if no handle is found and general rc otherwise */
2700 int __cifs_get_writable_file(struct cifsInodeInfo *cifs_inode,
2701 			     unsigned int find_flags, unsigned int open_flags,
2702 			     struct cifsFileInfo **ret_file)
2703 {
2704 	struct cifsFileInfo *open_file, *inv_file = NULL;
2705 	bool fsuid_only, with_delete;
2706 	struct cifs_sb_info *cifs_sb;
2707 	bool any_available = false;
2708 	unsigned int refind = 0;
2709 	*ret_file = NULL;
2710 	int rc = -EBADF;
2711 
2712 	/*
2713 	 * Having a null inode here (because mapping->host was set to zero by
2714 	 * the VFS or MM) should not happen but we had reports of on oops (due
2715 	 * to it being zero) during stress testcases so we need to check for it
2716 	 */
2717 
2718 	if (cifs_inode == NULL) {
2719 		cifs_dbg(VFS, "Null inode passed to cifs_writeable_file\n");
2720 		dump_stack();
2721 		return rc;
2722 	}
2723 
2724 	if (test_bit(CIFS_INO_TMPFILE, &cifs_inode->flags))
2725 		find_flags = FIND_ANY;
2726 
2727 	cifs_sb = CIFS_SB(cifs_inode);
2728 
2729 	with_delete = find_flags & FIND_WITH_DELETE;
2730 	fsuid_only = find_flags & FIND_FSUID_ONLY;
2731 	/* only filter by fsuid on multiuser mounts */
2732 	if (!(cifs_sb_flags(cifs_sb) & CIFS_MOUNT_MULTIUSER))
2733 		fsuid_only = false;
2734 
2735 	spin_lock(&cifs_inode->open_file_lock);
2736 refind_writable:
2737 	if (refind > MAX_REOPEN_ATT) {
2738 		spin_unlock(&cifs_inode->open_file_lock);
2739 		return rc;
2740 	}
2741 	list_for_each_entry(open_file, &cifs_inode->openFileList, flist) {
2742 		if (!any_available && open_file->pid != current->tgid)
2743 			continue;
2744 		if (fsuid_only && !uid_eq(open_file->uid, current_fsuid()))
2745 			continue;
2746 		if (with_delete && !(open_file->fid.access & DELETE))
2747 			continue;
2748 		if ((find_flags & FIND_NO_PENDING_DELETE) &&
2749 		    open_file->status_file_deleted)
2750 			continue;
2751 		if ((find_flags & FIND_OPEN_FLAGS) &&
2752 		    !open_flags_match(cifs_inode, open_flags,
2753 				      open_file->f_flags))
2754 			continue;
2755 		if (OPEN_FMODE(open_file->f_flags) & FMODE_WRITE) {
2756 			if (!open_file->invalidHandle) {
2757 				/* found a good writable file */
2758 				cifsFileInfo_get(open_file);
2759 				spin_unlock(&cifs_inode->open_file_lock);
2760 				*ret_file = open_file;
2761 				return 0;
2762 			} else {
2763 				if (!inv_file)
2764 					inv_file = open_file;
2765 			}
2766 		}
2767 	}
2768 	/* couldn't find usable FH with same pid, try any available */
2769 	if (!any_available) {
2770 		any_available = true;
2771 		goto refind_writable;
2772 	}
2773 
2774 	if (inv_file) {
2775 		any_available = false;
2776 		cifsFileInfo_get(inv_file);
2777 	}
2778 
2779 	spin_unlock(&cifs_inode->open_file_lock);
2780 
2781 	if (inv_file) {
2782 		rc = cifs_reopen_file(inv_file, false);
2783 		if (!rc) {
2784 			*ret_file = inv_file;
2785 			return 0;
2786 		}
2787 
2788 		spin_lock(&cifs_inode->open_file_lock);
2789 		list_move_tail(&inv_file->flist, &cifs_inode->openFileList);
2790 		spin_unlock(&cifs_inode->open_file_lock);
2791 		cifsFileInfo_put(inv_file);
2792 		++refind;
2793 		inv_file = NULL;
2794 		spin_lock(&cifs_inode->open_file_lock);
2795 		goto refind_writable;
2796 	}
2797 
2798 	return rc;
2799 }
2800 
2801 struct cifsFileInfo *
2802 find_writable_file(struct cifsInodeInfo *cifs_inode, int flags)
2803 {
2804 	struct cifsFileInfo *cfile;
2805 	int rc;
2806 
2807 	rc = cifs_get_writable_file(cifs_inode, flags, &cfile);
2808 	if (rc)
2809 		cifs_dbg(FYI, "Couldn't find writable handle rc=%d\n", rc);
2810 
2811 	return cfile;
2812 }
2813 
2814 int cifs_get_writable_path(struct cifs_tcon *tcon, const char *name,
2815 			   struct inode *inode, int flags,
2816 			   struct cifsFileInfo **ret_file)
2817 {
2818 	struct cifsFileInfo *cfile;
2819 	void *page;
2820 
2821 	*ret_file = NULL;
2822 
2823 	if (inode)
2824 		return cifs_get_writable_file(CIFS_I(inode), flags, ret_file);
2825 
2826 	page = alloc_dentry_path();
2827 	spin_lock(&tcon->open_file_lock);
2828 	list_for_each_entry(cfile, &tcon->openFileList, tlist) {
2829 		struct cifsInodeInfo *cinode;
2830 		const char *full_path = build_path_from_dentry(cfile->dentry, page);
2831 		if (IS_ERR(full_path)) {
2832 			spin_unlock(&tcon->open_file_lock);
2833 			free_dentry_path(page);
2834 			return PTR_ERR(full_path);
2835 		}
2836 		if (strcmp(full_path, name))
2837 			continue;
2838 
2839 		cinode = CIFS_I(d_inode(cfile->dentry));
2840 		spin_unlock(&tcon->open_file_lock);
2841 		free_dentry_path(page);
2842 		return cifs_get_writable_file(cinode, flags, ret_file);
2843 	}
2844 
2845 	spin_unlock(&tcon->open_file_lock);
2846 	free_dentry_path(page);
2847 	return -ENOENT;
2848 }
2849 
2850 int
2851 cifs_get_readable_path(struct cifs_tcon *tcon, const char *name,
2852 		       struct cifsFileInfo **ret_file)
2853 {
2854 	struct cifsFileInfo *cfile;
2855 	void *page = alloc_dentry_path();
2856 
2857 	*ret_file = NULL;
2858 
2859 	spin_lock(&tcon->open_file_lock);
2860 	list_for_each_entry(cfile, &tcon->openFileList, tlist) {
2861 		struct cifsInodeInfo *cinode;
2862 		const char *full_path = build_path_from_dentry(cfile->dentry, page);
2863 		if (IS_ERR(full_path)) {
2864 			spin_unlock(&tcon->open_file_lock);
2865 			free_dentry_path(page);
2866 			return PTR_ERR(full_path);
2867 		}
2868 		if (strcmp(full_path, name))
2869 			continue;
2870 
2871 		cinode = CIFS_I(d_inode(cfile->dentry));
2872 		spin_unlock(&tcon->open_file_lock);
2873 		free_dentry_path(page);
2874 		*ret_file = find_readable_file(cinode, FIND_ANY);
2875 		return *ret_file ? 0 : -ENOENT;
2876 	}
2877 
2878 	spin_unlock(&tcon->open_file_lock);
2879 	free_dentry_path(page);
2880 	return -ENOENT;
2881 }
2882 
2883 /*
2884  * Flush data on a strict file.
2885  */
2886 int cifs_strict_fsync(struct file *file, loff_t start, loff_t end,
2887 		      int datasync)
2888 {
2889 	struct cifsFileInfo *smbfile = file->private_data;
2890 	struct inode *inode = file_inode(file);
2891 	unsigned int xid;
2892 	int rc;
2893 
2894 	rc = file_write_and_wait_range(file, start, end);
2895 	if (rc) {
2896 		trace_cifs_fsync_err(inode->i_ino, rc);
2897 		return rc;
2898 	}
2899 
2900 	cifs_dbg(FYI, "%s: name=%pD datasync=0x%x\n", __func__, file, datasync);
2901 
2902 	if (!CIFS_CACHE_READ(CIFS_I(inode))) {
2903 		rc = cifs_zap_mapping(inode);
2904 		cifs_dbg(FYI, "%s: invalidate mapping: rc = %d\n", __func__, rc);
2905 	}
2906 
2907 	xid = get_xid();
2908 	rc = cifs_file_flush(xid, inode, smbfile);
2909 	free_xid(xid);
2910 	return rc;
2911 }
2912 
2913 /*
2914  * Flush data on a non-strict data.
2915  */
2916 int cifs_fsync(struct file *file, loff_t start, loff_t end, int datasync)
2917 {
2918 	unsigned int xid;
2919 	int rc = 0;
2920 	struct cifs_tcon *tcon;
2921 	struct TCP_Server_Info *server;
2922 	struct cifsFileInfo *smbfile = file->private_data;
2923 	struct inode *inode = file_inode(file);
2924 	struct cifs_sb_info *cifs_sb = CIFS_SB(file);
2925 
2926 	rc = file_write_and_wait_range(file, start, end);
2927 	if (rc) {
2928 		trace_cifs_fsync_err(file_inode(file)->i_ino, rc);
2929 		return rc;
2930 	}
2931 
2932 	xid = get_xid();
2933 
2934 	cifs_dbg(FYI, "Sync file - name: %pD datasync: 0x%x\n",
2935 		 file, datasync);
2936 
2937 	tcon = tlink_tcon(smbfile->tlink);
2938 	if (!(cifs_sb_flags(cifs_sb) & CIFS_MOUNT_NOSSYNC)) {
2939 		server = tcon->ses->server;
2940 		if (server->ops->flush == NULL) {
2941 			rc = -ENOSYS;
2942 			goto fsync_exit;
2943 		}
2944 
2945 		if ((OPEN_FMODE(smbfile->f_flags) & FMODE_WRITE) == 0) {
2946 			smbfile = find_writable_file(CIFS_I(inode), FIND_ANY);
2947 			if (smbfile) {
2948 				rc = server->ops->flush(xid, tcon, &smbfile->fid);
2949 				cifsFileInfo_put(smbfile);
2950 			} else
2951 				cifs_dbg(FYI, "ignore fsync for file not open for write\n");
2952 		} else
2953 			rc = server->ops->flush(xid, tcon, &smbfile->fid);
2954 	}
2955 
2956 fsync_exit:
2957 	free_xid(xid);
2958 	return rc;
2959 }
2960 
2961 /*
2962  * As file closes, flush all cached write data for this inode checking
2963  * for write behind errors.
2964  */
2965 int cifs_flush(struct file *file, fl_owner_t id)
2966 {
2967 	struct inode *inode = file_inode(file);
2968 	int rc = 0;
2969 
2970 	if (file->f_mode & FMODE_WRITE)
2971 		rc = filemap_write_and_wait(inode->i_mapping);
2972 
2973 	cifs_dbg(FYI, "Flush inode %p file %p rc %d\n", inode, file, rc);
2974 	if (rc) {
2975 		/* get more nuanced writeback errors */
2976 		rc = filemap_check_wb_err(file->f_mapping, 0);
2977 		trace_cifs_flush_err(inode->i_ino, rc);
2978 	}
2979 	return rc;
2980 }
2981 
2982 static ssize_t
2983 cifs_writev(struct kiocb *iocb, struct iov_iter *from)
2984 {
2985 	struct file *file = iocb->ki_filp;
2986 	struct cifsFileInfo *cfile = (struct cifsFileInfo *)file->private_data;
2987 	struct inode *inode = file->f_mapping->host;
2988 	struct cifsInodeInfo *cinode = CIFS_I(inode);
2989 	struct TCP_Server_Info *server = tlink_tcon(cfile->tlink)->ses->server;
2990 	struct cifs_sb_info *cifs_sb = CIFS_SB(inode);
2991 	ssize_t rc;
2992 
2993 	rc = netfs_start_io_write(inode);
2994 	if (rc < 0)
2995 		return rc;
2996 
2997 	/*
2998 	 * We need to hold the sem to be sure nobody modifies lock list
2999 	 * with a brlock that prevents writing.
3000 	 */
3001 	down_read(&cinode->lock_sem);
3002 
3003 	rc = generic_write_checks(iocb, from);
3004 	if (rc <= 0)
3005 		goto out;
3006 
3007 	if ((cifs_sb_flags(cifs_sb) & CIFS_MOUNT_NOPOSIXBRL) &&
3008 	    (cifs_find_lock_conflict(cfile, iocb->ki_pos, iov_iter_count(from),
3009 				     server->vals->exclusive_lock_type, 0,
3010 				     NULL, CIFS_WRITE_OP))) {
3011 		rc = -EACCES;
3012 		goto out;
3013 	}
3014 
3015 	rc = netfs_buffered_write_iter_locked(iocb, from, NULL);
3016 	cifs_update_i_blocks_after_write(iocb, rc);
3017 
3018 out:
3019 	up_read(&cinode->lock_sem);
3020 	netfs_end_io_write(inode);
3021 	if (rc > 0)
3022 		rc = generic_write_sync(iocb, rc);
3023 	return rc;
3024 }
3025 
3026 ssize_t
3027 cifs_strict_writev(struct kiocb *iocb, struct iov_iter *from)
3028 {
3029 	struct inode *inode = file_inode(iocb->ki_filp);
3030 	struct cifsInodeInfo *cinode = CIFS_I(inode);
3031 	struct cifs_sb_info *cifs_sb = CIFS_SB(inode);
3032 	struct cifsFileInfo *cfile = (struct cifsFileInfo *)
3033 						iocb->ki_filp->private_data;
3034 	struct cifs_tcon *tcon = tlink_tcon(cfile->tlink);
3035 	ssize_t written;
3036 
3037 	written = cifs_get_writer(cinode);
3038 	if (written)
3039 		return written;
3040 
3041 	if (CIFS_CACHE_WRITE(cinode)) {
3042 		if (cap_unix(tcon->ses) &&
3043 		    (CIFS_UNIX_FCNTL_CAP & le64_to_cpu(tcon->fsUnixInfo.Capability)) &&
3044 		    ((cifs_sb_flags(cifs_sb) & CIFS_MOUNT_NOPOSIXBRL) == 0)) {
3045 			written = netfs_file_write_iter(iocb, from);
3046 			cifs_update_i_blocks_after_write(iocb, written);
3047 			goto out;
3048 		}
3049 		written = cifs_writev(iocb, from);
3050 		goto out;
3051 	}
3052 	/*
3053 	 * For non-oplocked files in strict cache mode we need to write the data
3054 	 * to the server exactly from the pos to pos+len-1 rather than flush all
3055 	 * affected pages because it may cause a error with mandatory locks on
3056 	 * these pages but not on the region from pos to ppos+len-1.
3057 	 */
3058 	written = netfs_file_write_iter(iocb, from);
3059 	cifs_update_i_blocks_after_write(iocb, written);
3060 	if (CIFS_CACHE_READ(cinode)) {
3061 		/*
3062 		 * We have read level caching and we have just sent a write
3063 		 * request to the server thus making data in the cache stale.
3064 		 * Zap the cache and set oplock/lease level to NONE to avoid
3065 		 * reading stale data from the cache. All subsequent read
3066 		 * operations will read new data from the server.
3067 		 */
3068 		cifs_zap_mapping(inode);
3069 		cifs_dbg(FYI, "Set Oplock/Lease to NONE for inode=%p after write\n",
3070 			 inode);
3071 		cifs_reset_oplock(cinode);
3072 	}
3073 out:
3074 	cifs_put_writer(cinode);
3075 	return written;
3076 }
3077 
3078 ssize_t cifs_direct_write_iter(struct kiocb *iocb, struct iov_iter *from)
3079 {
3080 	ssize_t written;
3081 
3082 	written = netfs_file_write_iter(iocb, from);
3083 	cifs_update_i_blocks_after_write(iocb, written);
3084 	return written;
3085 }
3086 
3087 ssize_t cifs_loose_read_iter(struct kiocb *iocb, struct iov_iter *iter)
3088 {
3089 	ssize_t rc;
3090 	struct inode *inode = file_inode(iocb->ki_filp);
3091 
3092 	if (iocb->ki_flags & IOCB_DIRECT)
3093 		return netfs_unbuffered_read_iter(iocb, iter);
3094 
3095 	rc = cifs_revalidate_mapping(inode);
3096 	if (rc)
3097 		return rc;
3098 
3099 	return netfs_file_read_iter(iocb, iter);
3100 }
3101 
3102 ssize_t cifs_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
3103 {
3104 	struct inode *inode = file_inode(iocb->ki_filp);
3105 	struct cifsInodeInfo *cinode = CIFS_I(inode);
3106 	ssize_t written;
3107 	int rc;
3108 
3109 	if (iocb->ki_filp->f_flags & O_DIRECT) {
3110 		written = netfs_unbuffered_write_iter(iocb, from);
3111 		cifs_update_i_blocks_after_write(iocb, written);
3112 		if (written > 0 && CIFS_CACHE_READ(cinode)) {
3113 			cifs_zap_mapping(inode);
3114 			cifs_dbg(FYI,
3115 				 "Set no oplock for inode=%p after a write operation\n",
3116 				 inode);
3117 			cifs_reset_oplock(cinode);
3118 		}
3119 		return written;
3120 	}
3121 
3122 	written = cifs_get_writer(cinode);
3123 	if (written)
3124 		return written;
3125 
3126 	written = netfs_file_write_iter(iocb, from);
3127 	cifs_update_i_blocks_after_write(iocb, written);
3128 
3129 	if (!CIFS_CACHE_WRITE(CIFS_I(inode))) {
3130 		rc = filemap_fdatawrite(inode->i_mapping);
3131 		if (rc)
3132 			cifs_dbg(FYI, "cifs_file_write_iter: %d rc on %p inode\n",
3133 				 rc, inode);
3134 	}
3135 
3136 	cifs_put_writer(cinode);
3137 	return written;
3138 }
3139 
3140 ssize_t
3141 cifs_strict_readv(struct kiocb *iocb, struct iov_iter *to)
3142 {
3143 	struct inode *inode = file_inode(iocb->ki_filp);
3144 	struct cifsInodeInfo *cinode = CIFS_I(inode);
3145 	struct cifs_sb_info *cifs_sb = CIFS_SB(inode);
3146 	struct cifsFileInfo *cfile = (struct cifsFileInfo *)
3147 						iocb->ki_filp->private_data;
3148 	struct cifs_tcon *tcon = tlink_tcon(cfile->tlink);
3149 	int rc = -EACCES;
3150 
3151 	/*
3152 	 * In strict cache mode we need to read from the server all the time
3153 	 * if we don't have level II oplock because the server can delay mtime
3154 	 * change - so we can't make a decision about inode invalidating.
3155 	 * And we can also fail with pagereading if there are mandatory locks
3156 	 * on pages affected by this read but not on the region from pos to
3157 	 * pos+len-1.
3158 	 */
3159 	if (!CIFS_CACHE_READ(cinode))
3160 		return netfs_unbuffered_read_iter(iocb, to);
3161 
3162 	if ((cifs_sb_flags(cifs_sb) & CIFS_MOUNT_NOPOSIXBRL) == 0) {
3163 		if (iocb->ki_flags & IOCB_DIRECT)
3164 			return netfs_unbuffered_read_iter(iocb, to);
3165 		return netfs_buffered_read_iter(iocb, to);
3166 	}
3167 
3168 	/*
3169 	 * We need to hold the sem to be sure nobody modifies lock list
3170 	 * with a brlock that prevents reading.
3171 	 */
3172 	if (iocb->ki_flags & IOCB_DIRECT) {
3173 		rc = netfs_start_io_direct(inode);
3174 		if (rc < 0)
3175 			goto out;
3176 		rc = -EACCES;
3177 		down_read(&cinode->lock_sem);
3178 		if (!cifs_find_lock_conflict(
3179 			    cfile, iocb->ki_pos, iov_iter_count(to),
3180 			    tcon->ses->server->vals->shared_lock_type,
3181 			    0, NULL, CIFS_READ_OP))
3182 			rc = netfs_unbuffered_read_iter_locked(iocb, to);
3183 		up_read(&cinode->lock_sem);
3184 		netfs_end_io_direct(inode);
3185 	} else {
3186 		rc = netfs_start_io_read(inode);
3187 		if (rc < 0)
3188 			goto out;
3189 		rc = -EACCES;
3190 		down_read(&cinode->lock_sem);
3191 		if (!cifs_find_lock_conflict(
3192 			    cfile, iocb->ki_pos, iov_iter_count(to),
3193 			    tcon->ses->server->vals->shared_lock_type,
3194 			    0, NULL, CIFS_READ_OP))
3195 			rc = filemap_read(iocb, to, 0);
3196 		up_read(&cinode->lock_sem);
3197 		netfs_end_io_read(inode);
3198 	}
3199 out:
3200 	return rc;
3201 }
3202 
3203 static vm_fault_t cifs_page_mkwrite(struct vm_fault *vmf)
3204 {
3205 	return netfs_page_mkwrite(vmf, NULL);
3206 }
3207 
3208 static const struct vm_operations_struct cifs_file_vm_ops = {
3209 	.fault = filemap_fault,
3210 	.map_pages = filemap_map_pages,
3211 	.page_mkwrite = cifs_page_mkwrite,
3212 };
3213 
3214 int cifs_file_strict_mmap_prepare(struct vm_area_desc *desc)
3215 {
3216 	int xid, rc = 0;
3217 	struct inode *inode = file_inode(desc->file);
3218 
3219 	xid = get_xid();
3220 
3221 	if (!CIFS_CACHE_READ(CIFS_I(inode)))
3222 		rc = cifs_zap_mapping(inode);
3223 	if (!rc)
3224 		rc = generic_file_mmap_prepare(desc);
3225 	if (!rc)
3226 		desc->vm_ops = &cifs_file_vm_ops;
3227 
3228 	free_xid(xid);
3229 	return rc;
3230 }
3231 
3232 int cifs_file_mmap_prepare(struct vm_area_desc *desc)
3233 {
3234 	int rc, xid;
3235 
3236 	xid = get_xid();
3237 
3238 	rc = cifs_revalidate_file(desc->file);
3239 	if (rc)
3240 		cifs_dbg(FYI, "Validation prior to mmap failed, error=%d\n",
3241 			 rc);
3242 	if (!rc)
3243 		rc = generic_file_mmap_prepare(desc);
3244 	if (!rc)
3245 		desc->vm_ops = &cifs_file_vm_ops;
3246 
3247 	free_xid(xid);
3248 	return rc;
3249 }
3250 
3251 static int is_inode_writable(struct cifsInodeInfo *cifs_inode)
3252 {
3253 	struct cifsFileInfo *open_file;
3254 
3255 	spin_lock(&cifs_inode->open_file_lock);
3256 	list_for_each_entry(open_file, &cifs_inode->openFileList, flist) {
3257 		if (OPEN_FMODE(open_file->f_flags) & FMODE_WRITE) {
3258 			spin_unlock(&cifs_inode->open_file_lock);
3259 			return 1;
3260 		}
3261 	}
3262 	spin_unlock(&cifs_inode->open_file_lock);
3263 	return 0;
3264 }
3265 
3266 /* We do not want to update the file size from server for inodes
3267    open for write - to avoid races with writepage extending
3268    the file - in the future we could consider allowing
3269    refreshing the inode only on increases in the file size
3270    but this is tricky to do without racing with writebehind
3271    page caching in the current Linux kernel design */
3272 bool is_size_safe_to_change(struct cifsInodeInfo *cifsInode, __u64 end_of_file,
3273 			    bool from_readdir)
3274 {
3275 	struct cifs_sb_info *cifs_sb;
3276 	unsigned long tlw;
3277 
3278 	if (!cifsInode)
3279 		return true;
3280 
3281 	cifs_sb = CIFS_SB(cifsInode);
3282 
3283 	if (is_inode_writable(cifsInode) ||
3284 		((cifsInode->oplock & CIFS_CACHE_RW_FLG) != 0 && from_readdir)) {
3285 		/* This inode is open for write at least once */
3286 
3287 		/*
3288 		 * Readdir data is unreliable when we have writable handles or
3289 		 * an exclusive lease -- never allow it to change i_size, even
3290 		 * on direct-IO mounts where the server's directory metadata
3291 		 * can still lag behind the actual file state.
3292 		 */
3293 		if (from_readdir)
3294 			return false;
3295 
3296 		if (cifs_sb_flags(cifs_sb) & CIFS_MOUNT_DIRECT_IO) {
3297 			/* since no page cache to corrupt on directio
3298 			we can change size safely */
3299 			return true;
3300 		}
3301 
3302 		if (i_size_read(&cifsInode->netfs.inode) < end_of_file)
3303 			return true;
3304 
3305 		return false;
3306 	}
3307 
3308 	/*
3309 	 * No writable handles open. Check whether we are within the attribute
3310 	 * cache validity window of a recent local modification.
3311 	 *
3312 	 * For the close() path: _cifsFileInfo_put() stamps time_last_write
3313 	 * (via smp_store_release()) before releasing open_file_lock. That
3314 	 * spin_unlock() is a store-release that pairs with the spin_lock()
3315 	 * (load-acquire) in is_inode_writable() above, so if
3316 	 * is_inode_writable() returned false the smp_load_acquire() below is
3317 	 * guaranteed to observe any time_last_write update from a concurrent
3318 	 * close(), covering all close paths including background I/O.
3319 	 *
3320 	 * For the setattr/truncate paths: those callers use smp_store_release()
3321 	 * directly; the smp_load_acquire() below pairs with that store. There
3322 	 * is no shared lock between setattr and readdir, so this relies on
3323 	 * acquire-release semantics alone. The store propagation latency on
3324 	 * weakly-ordered architectures (nanoseconds) is negligible relative to
3325 	 * the acregmax window (seconds) and the readdir RPC round-trip
3326 	 * (milliseconds), making this a sound design choice in practice.
3327 	 *
3328 	 * time_last_write == 0 means the inode has never been written locally;
3329 	 * skip the window check to avoid false positives near boot time when
3330 	 * jiffies is still close to INITIAL_JIFFIES on 32-bit systems.
3331 	 */
3332 	if (from_readdir) {
3333 		/* Pairs with smp_store_release() in _cifsFileInfo_put() and setattr. */
3334 		tlw = smp_load_acquire(&cifsInode->time_last_write);
3335 		if (tlw && time_before(jiffies, tlw + cifs_sb->ctx->acregmax))
3336 			return false;
3337 	}
3338 
3339 	return true;
3340 }
3341 
3342 void cifs_oplock_break(struct work_struct *work)
3343 {
3344 	struct cifsFileInfo *cfile = container_of(work, struct cifsFileInfo,
3345 						  oplock_break);
3346 	struct inode *inode = d_inode(cfile->dentry);
3347 	struct super_block *sb = inode->i_sb;
3348 	struct cifs_sb_info *cifs_sb = CIFS_SB(sb);
3349 	struct cifsInodeInfo *cinode = CIFS_I(inode);
3350 	bool cache_read, cache_write, cache_handle;
3351 	struct cifs_tcon *tcon;
3352 	struct TCP_Server_Info *server;
3353 	struct tcon_link *tlink;
3354 	unsigned int oplock;
3355 	int rc = 0;
3356 	bool purge_cache = false, oplock_break_cancelled;
3357 	__u64 persistent_fid, volatile_fid;
3358 	__u16 net_fid;
3359 
3360 	wait_on_bit(&cinode->flags, CIFS_INODE_PENDING_WRITERS,
3361 			TASK_UNINTERRUPTIBLE);
3362 
3363 	tlink = cifs_get_tlink(cfile->tlink);
3364 	if (IS_ERR_OR_NULL(tlink)) {
3365 		/* drop the reference taken when the break was queued */
3366 		_cifsFileInfo_put(cfile, false /* do not wait for ourself */, false);
3367 		goto out;
3368 	}
3369 	tcon = tlink_tcon(tlink);
3370 	server = tcon->ses->server;
3371 
3372 	scoped_guard(spinlock, &cinode->open_file_lock) {
3373 		unsigned int sbflags = cifs_sb_flags(cifs_sb);
3374 
3375 		server->ops->downgrade_oplock(server, cinode, cfile->oplock_level,
3376 					      cfile->oplock_epoch, &purge_cache);
3377 		oplock = READ_ONCE(cinode->oplock);
3378 		cache_read = (oplock & CIFS_CACHE_READ_FLG) ||
3379 			(sbflags & CIFS_MOUNT_RO_CACHE);
3380 		cache_write = (oplock & CIFS_CACHE_WRITE_FLG) ||
3381 			(sbflags & CIFS_MOUNT_RW_CACHE);
3382 		cache_handle = oplock & CIFS_CACHE_HANDLE_FLG;
3383 	}
3384 
3385 	if (!cache_write && cache_read && cifs_has_mand_locks(cinode)) {
3386 		cifs_dbg(FYI, "Reset oplock to None for inode=%p due to mand locks\n",
3387 			 inode);
3388 		cifs_reset_oplock(cinode);
3389 		oplock = 0;
3390 		cache_read = cache_write = cache_handle = false;
3391 	}
3392 
3393 	if (S_ISREG(inode->i_mode)) {
3394 		if (cache_read)
3395 			break_lease(inode, O_RDONLY);
3396 		else
3397 			break_lease(inode, O_WRONLY);
3398 		rc = filemap_fdatawrite(inode->i_mapping);
3399 		if (!cache_read || purge_cache) {
3400 			rc = filemap_fdatawait(inode->i_mapping);
3401 			mapping_set_error(inode->i_mapping, rc);
3402 			cifs_zap_mapping(inode);
3403 		}
3404 		cifs_dbg(FYI, "Oplock flush inode %p rc %d\n", inode, rc);
3405 		if (cache_write)
3406 			goto oplock_break_ack;
3407 	}
3408 
3409 	rc = cifs_push_locks(cfile);
3410 	if (rc)
3411 		cifs_dbg(VFS, "Push locks rc = %d\n", rc);
3412 
3413 oplock_break_ack:
3414 	/*
3415 	 * When oplock break is received and there are no active
3416 	 * file handles but cached, then schedule deferred close immediately.
3417 	 * So, new open will not use cached handle.
3418 	 */
3419 
3420 	if (!cache_handle && !list_empty(&cinode->deferred_closes))
3421 		cifs_close_deferred_file(cinode);
3422 
3423 	persistent_fid = cfile->fid.persistent_fid;
3424 	volatile_fid = cfile->fid.volatile_fid;
3425 	net_fid = cfile->fid.netfid;
3426 	oplock_break_cancelled = cfile->oplock_break_cancelled;
3427 
3428 	_cifsFileInfo_put(cfile, false /* do not wait for ourself */, false);
3429 	/*
3430 	 * MS-SMB2 3.2.5.19.1 and 3.2.5.19.2 (and MS-CIFS 3.2.5.42) do not require
3431 	 * an acknowledgment to be sent when the file has already been closed.
3432 	 */
3433 	spin_lock(&cinode->open_file_lock);
3434 	/* check list empty since can race with kill_sb calling tree disconnect */
3435 	if (!oplock_break_cancelled && !list_empty(&cinode->openFileList)) {
3436 		spin_unlock(&cinode->open_file_lock);
3437 		rc = server->ops->oplock_response(tcon, persistent_fid,
3438 						  volatile_fid, net_fid,
3439 						  cinode, oplock);
3440 		cifs_dbg(FYI, "Oplock release rc = %d\n", rc);
3441 	} else
3442 		spin_unlock(&cinode->open_file_lock);
3443 
3444 	cifs_put_tlink(tlink);
3445 out:
3446 	cifs_done_oplock_break(cinode);
3447 }
3448 
3449 #ifdef CONFIG_SWAP
3450 static void cifs_swap_submit_write(struct swap_io_ctx *ctx)
3451 {
3452 	struct swap_iocb *sio = ctx->sio;
3453 	struct iov_iter iter;
3454 	int ret;
3455 
3456 	swap_fs_prepare_rw(ctx, WRITE, &iter);
3457 	ret = netfs_unbuffered_write_iter_locked(&sio->iocb, &iter, NULL);
3458 	if (ret != -EIOCBQUEUED)
3459 		sio->iocb.ki_complete(&sio->iocb, ret);
3460 }
3461 
3462 static void cifs_swap_submit_read(struct swap_io_ctx *ctx)
3463 {
3464 	struct swap_iocb *sio = ctx->sio;
3465 	struct iov_iter iter;
3466 	int ret;
3467 
3468 	swap_fs_prepare_rw(ctx, READ, &iter);
3469 	ret = netfs_unbuffered_read_iter_locked(&sio->iocb, &iter);
3470 	if (ret != -EIOCBQUEUED)
3471 		sio->iocb.ki_complete(&sio->iocb, ret);
3472 }
3473 
3474 static const struct swap_ops cifs_swap_ops = {
3475 	.flags			= SWAP_OPS_F_REQUIRE_NOFS,
3476 	.submit_write		= cifs_swap_submit_write,
3477 	.submit_read		= cifs_swap_submit_read,
3478 	.can_merge		= swap_fs_can_merge,
3479 };
3480 
3481 static int cifs_swap_activate(struct swap_info_struct *sis,
3482 			      struct file *swap_file, sector_t *span)
3483 {
3484 	struct cifsFileInfo *cfile = swap_file->private_data;
3485 	struct inode *inode = swap_file->f_mapping->host;
3486 	unsigned long blocks;
3487 	long long isize;
3488 
3489 	cifs_dbg(FYI, "swap activate\n");
3490 
3491 	if (swap_file->f_mapping->a_ops != &cifs_addr_ops)
3492 		/* Cannot support swap */
3493 		return -EINVAL;
3494 
3495 	spin_lock(&inode->i_lock);
3496 	blocks = inode->i_blocks;
3497 	isize = inode->i_size;
3498 	spin_unlock(&inode->i_lock);
3499 	if (blocks*512 < isize) {
3500 		pr_warn("swap activate: swapfile has holes\n");
3501 		return -EINVAL;
3502 	}
3503 	*span = sis->pages;
3504 
3505 	pr_warn_once("Swap support over SMB3 is experimental\n");
3506 
3507 	/*
3508 	 * TODO: consider adding ACL (or documenting how) to prevent other
3509 	 * users (on this or other systems) from reading it
3510 	 */
3511 
3512 
3513 	/* TODO: add sk_set_memalloc(inet) or similar */
3514 
3515 	if (cfile)
3516 		cfile->swapfile = true;
3517 	/*
3518 	 * TODO: Since file already open, we can't open with DENY_ALL here
3519 	 * but we could add call to grab a byte range lock to prevent others
3520 	 * from reading or writing the file
3521 	 */
3522 	return swap_fs_activate(sis, &cifs_swap_ops);
3523 }
3524 
3525 static void cifs_swap_deactivate(struct file *file)
3526 {
3527 	struct cifsFileInfo *cfile = file->private_data;
3528 
3529 	cifs_dbg(FYI, "swap deactivate\n");
3530 
3531 	/* TODO: undo sk_set_memalloc(inet) will eventually be needed */
3532 
3533 	if (cfile)
3534 		cfile->swapfile = false;
3535 
3536 	/* do we need to unpin (or unlock) the file */
3537 }
3538 #else
3539 #define cifs_swap_activate	NULL
3540 #define cifs_swap_deactivate	NULL
3541 #endif /* CONFIG_SWAP */
3542 
3543 const struct address_space_operations cifs_addr_ops = {
3544 	.read_folio	= netfs_read_folio,
3545 	.readahead	= netfs_readahead,
3546 	.writepages	= netfs_writepages,
3547 	.dirty_folio	= netfs_dirty_folio,
3548 	.release_folio	= netfs_release_folio,
3549 	.direct_IO	= noop_direct_IO,
3550 	.invalidate_folio = netfs_invalidate_folio,
3551 	.migrate_folio	= filemap_migrate_folio,
3552 	/*
3553 	 * TODO: investigate and if useful we could add an is_dirty_writeback
3554 	 * helper if needed
3555 	 */
3556 	.swap_activate	= cifs_swap_activate,
3557 	.swap_deactivate = cifs_swap_deactivate,
3558 };
3559 
3560 /*
3561  * cifs_readahead requires the server to support a buffer large enough to
3562  * contain the header plus one complete page of data.  Otherwise, we need
3563  * to leave cifs_readahead out of the address space operations.
3564  */
3565 const struct address_space_operations cifs_addr_ops_smallbuf = {
3566 	.read_folio	= netfs_read_folio,
3567 	.writepages	= netfs_writepages,
3568 	.dirty_folio	= netfs_dirty_folio,
3569 	.release_folio	= netfs_release_folio,
3570 	.invalidate_folio = netfs_invalidate_folio,
3571 	.migrate_folio	= filemap_migrate_folio,
3572 };
3573