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