xref: /linux/fs/nfs/write.c (revision 3e93d5bbcbfc3808f83712c0701f9d4c148cc8ed)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * linux/fs/nfs/write.c
4  *
5  * Write file data over NFS.
6  *
7  * Copyright (C) 1996, 1997, Olaf Kirch <okir@monad.swb.de>
8  */
9 
10 #include <linux/types.h>
11 #include <linux/slab.h>
12 #include <linux/mm.h>
13 #include <linux/pagemap.h>
14 #include <linux/file.h>
15 #include <linux/writeback.h>
16 #include <linux/swap.h>
17 #include <linux/migrate.h>
18 
19 #include <linux/sunrpc/clnt.h>
20 #include <linux/nfs_fs.h>
21 #include <linux/nfs_mount.h>
22 #include <linux/nfs_page.h>
23 #include <linux/backing-dev.h>
24 #include <linux/export.h>
25 #include <linux/freezer.h>
26 #include <linux/wait.h>
27 #include <linux/iversion.h>
28 #include <linux/filelock.h>
29 
30 #include <linux/uaccess.h>
31 #include <linux/sched/mm.h>
32 
33 #include "delegation.h"
34 #include "internal.h"
35 #include "iostat.h"
36 #include "nfs4_fs.h"
37 #include "fscache.h"
38 #include "pnfs.h"
39 
40 #include "nfstrace.h"
41 
42 #define NFSDBG_FACILITY		NFSDBG_PAGECACHE
43 
44 #define MIN_POOL_WRITE		(32)
45 #define MIN_POOL_COMMIT		(4)
46 
47 struct nfs_io_completion {
48 	void (*complete)(void *data);
49 	void *data;
50 	struct kref refcount;
51 };
52 
53 /*
54  * Local function declarations
55  */
56 static void nfs_redirty_request(struct nfs_page *req);
57 static const struct rpc_call_ops nfs_commit_ops;
58 static const struct nfs_pgio_completion_ops nfs_async_write_completion_ops;
59 static const struct nfs_commit_completion_ops nfs_commit_completion_ops;
60 static const struct nfs_rw_ops nfs_rw_write_ops;
61 static void nfs_inode_remove_request(struct nfs_page *req);
62 static void nfs_clear_request_commit(struct nfs_commit_info *cinfo,
63 				     struct nfs_page *req);
64 static void nfs_init_cinfo_from_inode(struct nfs_commit_info *cinfo,
65 				      struct inode *inode);
66 
67 static struct kmem_cache *nfs_wdata_cachep;
68 static mempool_t *nfs_wdata_mempool;
69 static struct kmem_cache *nfs_cdata_cachep;
70 static mempool_t *nfs_commit_mempool;
71 
nfs_commitdata_alloc(void)72 struct nfs_commit_data *nfs_commitdata_alloc(void)
73 {
74 	struct nfs_commit_data *p;
75 
76 	p = kmem_cache_zalloc(nfs_cdata_cachep, nfs_io_gfp_mask());
77 	if (!p) {
78 		p = mempool_alloc(nfs_commit_mempool, GFP_NOWAIT);
79 		if (!p)
80 			return NULL;
81 		memset(p, 0, sizeof(*p));
82 	}
83 	INIT_LIST_HEAD(&p->pages);
84 	return p;
85 }
86 EXPORT_SYMBOL_GPL(nfs_commitdata_alloc);
87 
nfs_commit_free(struct nfs_commit_data * p)88 void nfs_commit_free(struct nfs_commit_data *p)
89 {
90 	mempool_free(p, nfs_commit_mempool);
91 }
92 EXPORT_SYMBOL_GPL(nfs_commit_free);
93 
nfs_writehdr_alloc(void)94 static struct nfs_pgio_header *nfs_writehdr_alloc(void)
95 {
96 	struct nfs_pgio_header *p;
97 
98 	p = kmem_cache_zalloc(nfs_wdata_cachep, nfs_io_gfp_mask());
99 	if (!p) {
100 		p = mempool_alloc(nfs_wdata_mempool, GFP_NOWAIT);
101 		if (!p)
102 			return NULL;
103 		memset(p, 0, sizeof(*p));
104 	}
105 	p->rw_mode = FMODE_WRITE;
106 	return p;
107 }
108 
nfs_writehdr_free(struct nfs_pgio_header * hdr)109 static void nfs_writehdr_free(struct nfs_pgio_header *hdr)
110 {
111 	mempool_free(hdr, nfs_wdata_mempool);
112 }
113 
nfs_io_completion_alloc(gfp_t gfp_flags)114 static struct nfs_io_completion *nfs_io_completion_alloc(gfp_t gfp_flags)
115 {
116 	return kmalloc(sizeof(struct nfs_io_completion), gfp_flags);
117 }
118 
nfs_io_completion_init(struct nfs_io_completion * ioc,void (* complete)(void *),void * data)119 static void nfs_io_completion_init(struct nfs_io_completion *ioc,
120 		void (*complete)(void *), void *data)
121 {
122 	ioc->complete = complete;
123 	ioc->data = data;
124 	kref_init(&ioc->refcount);
125 }
126 
nfs_io_completion_release(struct kref * kref)127 static void nfs_io_completion_release(struct kref *kref)
128 {
129 	struct nfs_io_completion *ioc = container_of(kref,
130 			struct nfs_io_completion, refcount);
131 	ioc->complete(ioc->data);
132 	kfree(ioc);
133 }
134 
nfs_io_completion_get(struct nfs_io_completion * ioc)135 static void nfs_io_completion_get(struct nfs_io_completion *ioc)
136 {
137 	if (ioc != NULL)
138 		kref_get(&ioc->refcount);
139 }
140 
nfs_io_completion_put(struct nfs_io_completion * ioc)141 static void nfs_io_completion_put(struct nfs_io_completion *ioc)
142 {
143 	if (ioc != NULL)
144 		kref_put(&ioc->refcount, nfs_io_completion_release);
145 }
146 
147 static void
nfs_page_set_inode_ref(struct nfs_page * req,struct inode * inode)148 nfs_page_set_inode_ref(struct nfs_page *req, struct inode *inode)
149 {
150 	if (!test_and_set_bit(PG_INODE_REF, &req->wb_flags)) {
151 		kref_get(&req->wb_kref);
152 		atomic_long_inc(&NFS_I(inode)->nrequests);
153 	}
154 }
155 
nfs_cancel_remove_inode(struct nfs_page * req,struct inode * inode)156 static void nfs_cancel_remove_inode(struct nfs_page *req, struct inode *inode)
157 {
158 	if (test_and_clear_bit(PG_REMOVE, &req->wb_flags))
159 		nfs_page_set_inode_ref(req, inode);
160 }
161 
162 /**
163  * nfs_folio_find_head_request - find head request associated with a folio
164  * @folio: pointer to folio
165  *
166  * must be called while holding the inode lock.
167  *
168  * returns matching head request with reference held, or NULL if not found.
169  */
nfs_folio_find_head_request(struct folio * folio)170 static struct nfs_page *nfs_folio_find_head_request(struct folio *folio)
171 {
172 	struct address_space *mapping = folio->mapping;
173 	struct nfs_page *req;
174 
175 	if (!folio_test_private(folio))
176 		return NULL;
177 	spin_lock(&mapping->i_private_lock);
178 	req = folio->private;
179 	if (req) {
180 		WARN_ON_ONCE(req->wb_head != req);
181 		kref_get(&req->wb_kref);
182 	}
183 	spin_unlock(&mapping->i_private_lock);
184 	return req;
185 }
186 
187 /* Adjust the file length if we're writing beyond the end */
nfs_grow_file(struct folio * folio,unsigned int offset,unsigned int count)188 static void nfs_grow_file(struct folio *folio, unsigned int offset,
189 			  unsigned int count)
190 {
191 	struct inode *inode = folio->mapping->host;
192 	loff_t end, i_size;
193 	pgoff_t end_index;
194 
195 	spin_lock(&inode->i_lock);
196 	i_size = i_size_read(inode);
197 	end_index = ((i_size - 1) >> folio_shift(folio)) << folio_order(folio);
198 	if (i_size > 0 && folio->index < end_index)
199 		goto out;
200 	end = folio_pos(folio) + (loff_t)offset + (loff_t)count;
201 	if (i_size >= end)
202 		goto out;
203 	trace_nfs_size_grow(inode, end);
204 	i_size_write(inode, end);
205 	NFS_I(inode)->cache_validity &= ~NFS_INO_INVALID_SIZE;
206 	nfs_inc_stats(inode, NFSIOS_EXTENDWRITE);
207 out:
208 	/* Atomically update timestamps if they are delegated to us. */
209 	nfs_update_delegated_mtime_locked(inode);
210 	spin_unlock(&inode->i_lock);
211 	nfs_fscache_invalidate(inode, 0);
212 }
213 
214 /* A writeback failed: mark the page as bad, and invalidate the page cache */
nfs_set_pageerror(struct address_space * mapping)215 static void nfs_set_pageerror(struct address_space *mapping)
216 {
217 	struct inode *inode = mapping->host;
218 
219 	nfs_zap_mapping(mapping->host, mapping);
220 	/* Force file size revalidation */
221 	spin_lock(&inode->i_lock);
222 	nfs_set_cache_invalid(inode, NFS_INO_REVAL_FORCED |
223 					     NFS_INO_INVALID_CHANGE |
224 					     NFS_INO_INVALID_SIZE);
225 	spin_unlock(&inode->i_lock);
226 }
227 
nfs_mapping_set_error(struct folio * folio,int error)228 static void nfs_mapping_set_error(struct folio *folio, int error)
229 {
230 	struct address_space *mapping = folio->mapping;
231 
232 	filemap_set_wb_err(mapping, error);
233 	if (mapping->host)
234 		errseq_set(&mapping->host->i_sb->s_wb_err,
235 			   error == -ENOSPC ? -ENOSPC : -EIO);
236 	nfs_set_pageerror(mapping);
237 }
238 
239 /*
240  * nfs_page_group_search_locked
241  * @head - head request of page group
242  * @page_offset - offset into page
243  *
244  * Search page group with head @head to find a request that contains the
245  * page offset @page_offset.
246  *
247  * Returns a pointer to the first matching nfs request, or NULL if no
248  * match is found.
249  *
250  * Must be called with the page group lock held
251  */
252 static struct nfs_page *
nfs_page_group_search_locked(struct nfs_page * head,unsigned int page_offset)253 nfs_page_group_search_locked(struct nfs_page *head, unsigned int page_offset)
254 {
255 	struct nfs_page *req;
256 
257 	req = head;
258 	do {
259 		if (page_offset >= req->wb_pgbase &&
260 		    page_offset < (req->wb_pgbase + req->wb_bytes))
261 			return req;
262 
263 		req = req->wb_this_page;
264 	} while (req != head);
265 
266 	return NULL;
267 }
268 
269 /*
270  * nfs_page_group_covers_page
271  * @head - head request of page group
272  *
273  * Return true if the page group with head @head covers the whole page,
274  * returns false otherwise
275  */
nfs_page_group_covers_page(struct nfs_page * req)276 static bool nfs_page_group_covers_page(struct nfs_page *req)
277 {
278 	unsigned int len = nfs_folio_length(nfs_page_to_folio(req));
279 	struct nfs_page *tmp;
280 	unsigned int pos = 0;
281 
282 	nfs_page_group_lock(req);
283 
284 	for (;;) {
285 		tmp = nfs_page_group_search_locked(req->wb_head, pos);
286 		if (!tmp)
287 			break;
288 		pos = tmp->wb_pgbase + tmp->wb_bytes;
289 	}
290 
291 	nfs_page_group_unlock(req);
292 	return pos >= len;
293 }
294 
295 /* We can set the PG_uptodate flag if we see that a write request
296  * covers the full page.
297  */
nfs_mark_uptodate(struct nfs_page * req)298 static void nfs_mark_uptodate(struct nfs_page *req)
299 {
300 	struct folio *folio = nfs_page_to_folio(req);
301 
302 	if (folio_test_uptodate(folio))
303 		return;
304 	if (!nfs_page_group_covers_page(req))
305 		return;
306 	folio_mark_uptodate(folio);
307 }
308 
wb_priority(struct writeback_control * wbc)309 static int wb_priority(struct writeback_control *wbc)
310 {
311 	int ret = 0;
312 
313 	if (wbc->sync_mode == WB_SYNC_ALL)
314 		ret = FLUSH_COND_STABLE;
315 	return ret;
316 }
317 
318 /*
319  * NFS congestion control
320  */
321 
322 int nfs_congestion_kb;
323 
324 #define NFS_CONGESTION_ON_THRESH 	(nfs_congestion_kb >> (PAGE_SHIFT-10))
325 #define NFS_CONGESTION_OFF_THRESH	\
326 	(NFS_CONGESTION_ON_THRESH - (NFS_CONGESTION_ON_THRESH >> 2))
327 
nfs_folio_set_writeback(struct folio * folio)328 static void nfs_folio_set_writeback(struct folio *folio)
329 {
330 	struct nfs_server *nfss = NFS_SERVER(folio->mapping->host);
331 
332 	folio_start_writeback(folio);
333 	if (atomic_long_inc_return(&nfss->writeback) > NFS_CONGESTION_ON_THRESH)
334 		nfss->write_congested = 1;
335 }
336 
nfs_folio_end_writeback(struct folio * folio)337 static void nfs_folio_end_writeback(struct folio *folio)
338 {
339 	struct nfs_server *nfss = NFS_SERVER(folio->mapping->host);
340 
341 	folio_end_writeback(folio);
342 	if (atomic_long_dec_return(&nfss->writeback) <
343 	    NFS_CONGESTION_OFF_THRESH) {
344 		nfss->write_congested = 0;
345 		wake_up_all(&nfss->write_congestion_wait);
346 	}
347 }
348 
nfs_page_end_writeback(struct nfs_page * req)349 static void nfs_page_end_writeback(struct nfs_page *req)
350 {
351 	if (nfs_page_group_sync_on_bit(req, PG_WB_END)) {
352 		nfs_unlock_request(req);
353 		nfs_folio_end_writeback(nfs_page_to_folio(req));
354 	} else
355 		nfs_unlock_request(req);
356 }
357 
358 /*
359  * nfs_destroy_unlinked_subrequests - destroy recently unlinked subrequests
360  *
361  * @destroy_list - request list (using wb_this_page) terminated by @old_head
362  * @old_head - the old head of the list
363  *
364  * All subrequests must be locked and removed from all lists, so at this point
365  * they are only "active" in this function, and possibly in nfs_wait_on_request
366  * with a reference held by some other context.
367  */
368 static void
nfs_destroy_unlinked_subrequests(struct nfs_page * destroy_list,struct nfs_page * old_head,struct inode * inode)369 nfs_destroy_unlinked_subrequests(struct nfs_page *destroy_list,
370 				 struct nfs_page *old_head,
371 				 struct inode *inode)
372 {
373 	while (destroy_list) {
374 		struct nfs_page *subreq = destroy_list;
375 
376 		destroy_list = (subreq->wb_this_page == old_head) ?
377 				   NULL : subreq->wb_this_page;
378 
379 		/* Note: lock subreq in order to change subreq->wb_head */
380 		nfs_page_set_headlock(subreq);
381 		WARN_ON_ONCE(old_head != subreq->wb_head);
382 
383 		/* make sure old group is not used */
384 		subreq->wb_this_page = subreq;
385 		subreq->wb_head = subreq;
386 
387 		clear_bit(PG_REMOVE, &subreq->wb_flags);
388 
389 		/* Note: races with nfs_page_group_destroy() */
390 		if (!kref_read(&subreq->wb_kref)) {
391 			/* Check if we raced with nfs_page_group_destroy() */
392 			if (test_and_clear_bit(PG_TEARDOWN, &subreq->wb_flags)) {
393 				nfs_page_clear_headlock(subreq);
394 				nfs_free_request(subreq);
395 			} else
396 				nfs_page_clear_headlock(subreq);
397 			continue;
398 		}
399 		nfs_page_clear_headlock(subreq);
400 
401 		nfs_release_request(old_head);
402 
403 		if (test_and_clear_bit(PG_INODE_REF, &subreq->wb_flags)) {
404 			nfs_release_request(subreq);
405 			atomic_long_dec(&NFS_I(inode)->nrequests);
406 		}
407 
408 		/* subreq is now totally disconnected from page group or any
409 		 * write / commit lists. last chance to wake any waiters */
410 		nfs_unlock_and_release_request(subreq);
411 	}
412 }
413 
414 /*
415  * nfs_join_page_group - destroy subrequests of the head req
416  * @head: the page used to lookup the "page group" of nfs_page structures
417  * @inode: Inode to which the request belongs.
418  *
419  * This function joins all sub requests to the head request by first
420  * locking all requests in the group, cancelling any pending operations
421  * and finally updating the head request to cover the whole range covered by
422  * the (former) group.  All subrequests are removed from any write or commit
423  * lists, unlinked from the group and destroyed.
424  */
nfs_join_page_group(struct nfs_page * head,struct nfs_commit_info * cinfo,struct inode * inode)425 void nfs_join_page_group(struct nfs_page *head, struct nfs_commit_info *cinfo,
426 			 struct inode *inode)
427 {
428 	struct nfs_page *subreq;
429 	struct nfs_page *destroy_list = NULL;
430 	unsigned int pgbase, off, bytes;
431 
432 	pgbase = head->wb_pgbase;
433 	bytes = head->wb_bytes;
434 	off = head->wb_offset;
435 	for (subreq = head->wb_this_page; subreq != head;
436 			subreq = subreq->wb_this_page) {
437 		/* Subrequests should always form a contiguous range */
438 		if (pgbase > subreq->wb_pgbase) {
439 			off -= pgbase - subreq->wb_pgbase;
440 			bytes += pgbase - subreq->wb_pgbase;
441 			pgbase = subreq->wb_pgbase;
442 		}
443 		bytes = max(subreq->wb_pgbase + subreq->wb_bytes
444 				- pgbase, bytes);
445 	}
446 
447 	/* Set the head request's range to cover the former page group */
448 	head->wb_pgbase = pgbase;
449 	head->wb_bytes = bytes;
450 	head->wb_offset = off;
451 
452 	/* Now that all requests are locked, make sure they aren't on any list.
453 	 * Commit list removal accounting is done after locks are dropped */
454 	subreq = head;
455 	do {
456 		nfs_clear_request_commit(cinfo, subreq);
457 		subreq = subreq->wb_this_page;
458 	} while (subreq != head);
459 
460 	/* unlink subrequests from head, destroy them later */
461 	if (head->wb_this_page != head) {
462 		/* destroy list will be terminated by head */
463 		destroy_list = head->wb_this_page;
464 		head->wb_this_page = head;
465 	}
466 
467 	nfs_destroy_unlinked_subrequests(destroy_list, head, inode);
468 }
469 
470 /**
471  * nfs_wait_on_request - Wait for a request to complete.
472  * @req: request to wait upon.
473  *
474  * Interruptible by fatal signals only.
475  * The user is responsible for holding a count on the request.
476  */
nfs_wait_on_request(struct nfs_page * req)477 static int nfs_wait_on_request(struct nfs_page *req)
478 {
479 	if (!test_bit(PG_BUSY, &req->wb_flags))
480 		return 0;
481 	set_bit(PG_CONTENDED2, &req->wb_flags);
482 	smp_mb__after_atomic();
483 	return wait_on_bit_io(&req->wb_flags, PG_BUSY,
484 			      TASK_UNINTERRUPTIBLE);
485 }
486 
487 /*
488  * nfs_unroll_locks -  unlock all newly locked reqs and wait on @req
489  * @head: head request of page group, must be holding head lock
490  * @req: request that couldn't lock and needs to wait on the req bit lock
491  *
492  * This is a helper function for nfs_lock_and_join_requests
493  * returns 0 on success, < 0 on error.
494  */
495 static void
nfs_unroll_locks(struct nfs_page * head,struct nfs_page * req)496 nfs_unroll_locks(struct nfs_page *head, struct nfs_page *req)
497 {
498 	struct nfs_page *tmp;
499 
500 	/* relinquish all the locks successfully grabbed this run */
501 	for (tmp = head->wb_this_page ; tmp != req; tmp = tmp->wb_this_page) {
502 		if (!kref_read(&tmp->wb_kref))
503 			continue;
504 		nfs_unlock_and_release_request(tmp);
505 	}
506 }
507 
508 /*
509  * nfs_page_group_lock_subreq -  try to lock a subrequest
510  * @head: head request of page group
511  * @subreq: request to lock
512  *
513  * This is a helper function for nfs_lock_and_join_requests which
514  * must be called with the head request and page group both locked.
515  * On error, it returns with the page group unlocked.
516  */
517 static int
nfs_page_group_lock_subreq(struct nfs_page * head,struct nfs_page * subreq)518 nfs_page_group_lock_subreq(struct nfs_page *head, struct nfs_page *subreq)
519 {
520 	int ret;
521 
522 	if (!kref_get_unless_zero(&subreq->wb_kref))
523 		return 0;
524 	while (!nfs_lock_request(subreq)) {
525 		nfs_page_group_unlock(head);
526 		ret = nfs_wait_on_request(subreq);
527 		if (!ret)
528 			ret = nfs_page_group_lock(head);
529 		if (ret < 0) {
530 			nfs_unroll_locks(head, subreq);
531 			nfs_release_request(subreq);
532 			return ret;
533 		}
534 	}
535 	return 0;
536 }
537 
538 /*
539  * nfs_lock_and_join_requests - join all subreqs to the head req
540  * @folio: the folio used to lookup the "page group" of nfs_page structures
541  *
542  * This function joins all sub requests to the head request by first
543  * locking all requests in the group, cancelling any pending operations
544  * and finally updating the head request to cover the whole range covered by
545  * the (former) group.  All subrequests are removed from any write or commit
546  * lists, unlinked from the group and destroyed.
547  *
548  * Returns a locked, referenced pointer to the head request - which after
549  * this call is guaranteed to be the only request associated with the page.
550  * Returns NULL if no requests are found for @folio, or a ERR_PTR if an
551  * error was encountered.
552  */
nfs_lock_and_join_requests(struct folio * folio)553 static struct nfs_page *nfs_lock_and_join_requests(struct folio *folio)
554 {
555 	struct inode *inode = folio->mapping->host;
556 	struct nfs_page *head, *subreq;
557 	struct nfs_commit_info cinfo;
558 	int ret;
559 
560 	/*
561 	 * A reference is taken only on the head request which acts as a
562 	 * reference to the whole page group - the group will not be destroyed
563 	 * until the head reference is released.
564 	 */
565 retry:
566 	head = nfs_folio_find_head_request(folio);
567 	if (!head)
568 		return NULL;
569 
570 	while (!nfs_lock_request(head)) {
571 		ret = nfs_wait_on_request(head);
572 		if (ret < 0) {
573 			nfs_release_request(head);
574 			return ERR_PTR(ret);
575 		}
576 	}
577 
578 	ret = nfs_page_group_lock(head);
579 	if (ret < 0)
580 		goto out_unlock;
581 
582 	/* Ensure that nobody removed the request before we locked it */
583 	if (head != folio->private) {
584 		nfs_page_group_unlock(head);
585 		nfs_unlock_and_release_request(head);
586 		goto retry;
587 	}
588 
589 	nfs_cancel_remove_inode(head, inode);
590 
591 	/* lock each request in the page group */
592 	for (subreq = head->wb_this_page;
593 	     subreq != head;
594 	     subreq = subreq->wb_this_page) {
595 		ret = nfs_page_group_lock_subreq(head, subreq);
596 		if (ret < 0)
597 			goto out_unlock;
598 	}
599 
600 	nfs_page_group_unlock(head);
601 
602 	nfs_init_cinfo_from_inode(&cinfo, inode);
603 	nfs_join_page_group(head, &cinfo, inode);
604 	return head;
605 
606 out_unlock:
607 	nfs_unlock_and_release_request(head);
608 	return ERR_PTR(ret);
609 }
610 
nfs_write_error(struct nfs_page * req,int error)611 static void nfs_write_error(struct nfs_page *req, int error)
612 {
613 	trace_nfs_write_error(nfs_page_to_inode(req), req, error);
614 	nfs_mapping_set_error(nfs_page_to_folio(req), error);
615 	nfs_inode_remove_request(req);
616 	nfs_page_end_writeback(req);
617 	nfs_release_request(req);
618 }
619 
620 /*
621  * Find an associated nfs write request, and prepare to flush it out
622  * May return an error if the user signalled nfs_wait_on_request().
623  */
nfs_do_writepage(struct folio * folio,struct writeback_control * wbc,struct nfs_pageio_descriptor * pgio)624 static int nfs_do_writepage(struct folio *folio, struct writeback_control *wbc,
625 		struct nfs_pageio_descriptor *pgio)
626 {
627 	struct nfs_page *req;
628 	int ret;
629 
630 	nfs_pageio_cond_complete(pgio, folio->index);
631 
632 	req = nfs_lock_and_join_requests(folio);
633 	if (!req)
634 		return 0;
635 	if (IS_ERR(req))
636 		return PTR_ERR(req);
637 
638 	nfs_folio_set_writeback(folio);
639 	WARN_ON_ONCE(test_bit(PG_CLEAN, &req->wb_flags));
640 
641 	/* If there is a fatal error that covers this write, just exit */
642 	ret = pgio->pg_error;
643 	if (nfs_error_is_fatal_on_server(ret))
644 		goto out_launder;
645 
646 	if (!nfs_pageio_add_request(pgio, req)) {
647 		ret = pgio->pg_error;
648 		/*
649 		 * Remove the problematic req upon fatal errors on the server
650 		 */
651 		if (nfs_error_is_fatal_on_server(ret))
652 			goto out_launder;
653 		folio_redirty_for_writepage(wbc, folio);
654 		nfs_redirty_request(req);
655 		pgio->pg_error = 0;
656 		return ret;
657 	}
658 
659 	nfs_add_stats(folio->mapping->host, NFSIOS_WRITEPAGES, 1);
660 	return 0;
661 
662 out_launder:
663 	nfs_write_error(req, ret);
664 	return 0;
665 }
666 
667 /*
668  * Write an mmapped page to the server.
669  */
nfs_writepage_locked(struct folio * folio,struct writeback_control * wbc)670 static int nfs_writepage_locked(struct folio *folio,
671 				struct writeback_control *wbc)
672 {
673 	struct nfs_pageio_descriptor pgio;
674 	struct inode *inode = folio->mapping->host;
675 	int err;
676 
677 	nfs_inc_stats(inode, NFSIOS_VFSWRITEPAGE);
678 	nfs_pageio_init_write(&pgio, inode, 0, false,
679 			      &nfs_async_write_completion_ops);
680 	err = nfs_do_writepage(folio, wbc, &pgio);
681 	pgio.pg_error = 0;
682 	nfs_pageio_complete(&pgio);
683 	return err;
684 }
685 
nfs_io_completion_commit(void * inode)686 static void nfs_io_completion_commit(void *inode)
687 {
688 	nfs_commit_inode(inode, 0);
689 }
690 
nfs_writepages(struct address_space * mapping,struct writeback_control * wbc)691 int nfs_writepages(struct address_space *mapping, struct writeback_control *wbc)
692 {
693 	struct inode *inode = mapping->host;
694 	struct nfs_pageio_descriptor pgio;
695 	struct nfs_io_completion *ioc = NULL;
696 	unsigned int mntflags = NFS_SERVER(inode)->flags;
697 	struct nfs_server *nfss = NFS_SERVER(inode);
698 	int priority = 0;
699 	int err;
700 
701 	/* Wait with writeback until write congestion eases */
702 	if (wbc->sync_mode == WB_SYNC_NONE && nfss->write_congested) {
703 		err = wait_event_killable(nfss->write_congestion_wait,
704 					  nfss->write_congested == 0);
705 		if (err)
706 			return err;
707 	}
708 
709 	nfs_inc_stats(inode, NFSIOS_VFSWRITEPAGES);
710 
711 	if (!(mntflags & NFS_MOUNT_WRITE_EAGER) || wbc->for_kupdate ||
712 	    wbc->for_background || wbc->for_sync) {
713 		ioc = nfs_io_completion_alloc(GFP_KERNEL);
714 		if (ioc)
715 			nfs_io_completion_init(ioc, nfs_io_completion_commit,
716 					       inode);
717 		priority = wb_priority(wbc);
718 	}
719 
720 	do {
721 		struct folio *folio = NULL;
722 
723 		nfs_pageio_init_write(&pgio, inode, priority, false,
724 				      &nfs_async_write_completion_ops);
725 		pgio.pg_io_completion = ioc;
726 		while ((folio = writeback_iter(mapping, wbc, folio, &err))) {
727 			err = nfs_do_writepage(folio, wbc, &pgio);
728 			folio_unlock(folio);
729 		}
730 		pgio.pg_error = 0;
731 		nfs_pageio_complete(&pgio);
732 		if (err == -EAGAIN && mntflags & NFS_MOUNT_SOFTERR)
733 			break;
734 	} while (err < 0 && !nfs_error_is_fatal(err));
735 	nfs_io_completion_put(ioc);
736 
737 	if (err < 0)
738 		goto out_err;
739 	return 0;
740 out_err:
741 	return err;
742 }
743 
744 /*
745  * Insert a write request into an inode
746  */
nfs_inode_add_request(struct nfs_page * req)747 static void nfs_inode_add_request(struct nfs_page *req)
748 {
749 	struct folio *folio = nfs_page_to_folio(req);
750 	struct address_space *mapping = folio->mapping;
751 	struct nfs_inode *nfsi = NFS_I(mapping->host);
752 
753 	WARN_ON_ONCE(req->wb_this_page != req);
754 
755 	/* Lock the request! */
756 	nfs_lock_request(req);
757 	spin_lock(&mapping->i_private_lock);
758 	set_bit(PG_MAPPED, &req->wb_flags);
759 	folio_set_private(folio);
760 	folio->private = req;
761 	spin_unlock(&mapping->i_private_lock);
762 	atomic_long_inc(&nfsi->nrequests);
763 	/* this a head request for a page group - mark it as having an
764 	 * extra reference so sub groups can follow suit.
765 	 * This flag also informs pgio layer when to bump nrequests when
766 	 * adding subrequests. */
767 	WARN_ON(test_and_set_bit(PG_INODE_REF, &req->wb_flags));
768 	kref_get(&req->wb_kref);
769 }
770 
771 /*
772  * Remove a write request from an inode
773  */
nfs_inode_remove_request(struct nfs_page * req)774 static void nfs_inode_remove_request(struct nfs_page *req)
775 {
776 	struct nfs_inode *nfsi = NFS_I(nfs_page_to_inode(req));
777 
778 	nfs_page_group_lock(req);
779 	if (nfs_page_group_sync_on_bit_locked(req, PG_REMOVE)) {
780 		struct folio *folio = nfs_page_to_folio(req->wb_head);
781 		struct address_space *mapping = folio->mapping;
782 
783 		spin_lock(&mapping->i_private_lock);
784 		if (likely(folio)) {
785 			folio->private = NULL;
786 			folio_clear_private(folio);
787 			clear_bit(PG_MAPPED, &req->wb_head->wb_flags);
788 		}
789 		spin_unlock(&mapping->i_private_lock);
790 	}
791 	nfs_page_group_unlock(req);
792 
793 	if (test_and_clear_bit(PG_INODE_REF, &req->wb_flags)) {
794 		atomic_long_dec(&nfsi->nrequests);
795 		nfs_release_request(req);
796 	}
797 }
798 
nfs_mark_request_dirty(struct nfs_page * req)799 static void nfs_mark_request_dirty(struct nfs_page *req)
800 {
801 	struct folio *folio = nfs_page_to_folio(req);
802 	if (folio)
803 		filemap_dirty_folio(folio_mapping(folio), folio);
804 }
805 
806 /**
807  * nfs_request_add_commit_list_locked - add request to a commit list
808  * @req: pointer to a struct nfs_page
809  * @dst: commit list head
810  * @cinfo: holds list lock and accounting info
811  *
812  * This sets the PG_CLEAN bit, updates the cinfo count of
813  * number of outstanding requests requiring a commit as well as
814  * the MM page stats.
815  *
816  * The caller must hold NFS_I(cinfo->inode)->commit_mutex, and the
817  * nfs_page lock.
818  */
819 void
nfs_request_add_commit_list_locked(struct nfs_page * req,struct list_head * dst,struct nfs_commit_info * cinfo)820 nfs_request_add_commit_list_locked(struct nfs_page *req, struct list_head *dst,
821 			    struct nfs_commit_info *cinfo)
822 {
823 	set_bit(PG_CLEAN, &req->wb_flags);
824 	nfs_list_add_request(req, dst);
825 	atomic_long_inc(&cinfo->mds->ncommit);
826 }
827 EXPORT_SYMBOL_GPL(nfs_request_add_commit_list_locked);
828 
829 /**
830  * nfs_request_add_commit_list - add request to a commit list
831  * @req: pointer to a struct nfs_page
832  * @cinfo: holds list lock and accounting info
833  *
834  * This sets the PG_CLEAN bit, updates the cinfo count of
835  * number of outstanding requests requiring a commit as well as
836  * the MM page stats.
837  *
838  * The caller must _not_ hold the cinfo->lock, but must be
839  * holding the nfs_page lock.
840  */
841 void
nfs_request_add_commit_list(struct nfs_page * req,struct nfs_commit_info * cinfo)842 nfs_request_add_commit_list(struct nfs_page *req, struct nfs_commit_info *cinfo)
843 {
844 	mutex_lock(&NFS_I(cinfo->inode)->commit_mutex);
845 	nfs_request_add_commit_list_locked(req, &cinfo->mds->list, cinfo);
846 	mutex_unlock(&NFS_I(cinfo->inode)->commit_mutex);
847 	nfs_folio_mark_unstable(nfs_page_to_folio(req), cinfo);
848 }
849 EXPORT_SYMBOL_GPL(nfs_request_add_commit_list);
850 
851 /**
852  * nfs_request_remove_commit_list - Remove request from a commit list
853  * @req: pointer to a nfs_page
854  * @cinfo: holds list lock and accounting info
855  *
856  * This clears the PG_CLEAN bit, and updates the cinfo's count of
857  * number of outstanding requests requiring a commit
858  * It does not update the MM page stats.
859  *
860  * The caller _must_ hold the cinfo->lock and the nfs_page lock.
861  */
862 void
nfs_request_remove_commit_list(struct nfs_page * req,struct nfs_commit_info * cinfo)863 nfs_request_remove_commit_list(struct nfs_page *req,
864 			       struct nfs_commit_info *cinfo)
865 {
866 	if (!test_and_clear_bit(PG_CLEAN, &(req)->wb_flags))
867 		return;
868 	nfs_list_remove_request(req);
869 	atomic_long_dec(&cinfo->mds->ncommit);
870 }
871 EXPORT_SYMBOL_GPL(nfs_request_remove_commit_list);
872 
nfs_init_cinfo_from_inode(struct nfs_commit_info * cinfo,struct inode * inode)873 static void nfs_init_cinfo_from_inode(struct nfs_commit_info *cinfo,
874 				      struct inode *inode)
875 {
876 	cinfo->inode = inode;
877 	cinfo->mds = &NFS_I(inode)->commit_info;
878 	cinfo->ds = pnfs_get_ds_info(inode);
879 	cinfo->dreq = NULL;
880 	cinfo->completion_ops = &nfs_commit_completion_ops;
881 }
882 
nfs_init_cinfo(struct nfs_commit_info * cinfo,struct inode * inode,struct nfs_direct_req * dreq)883 void nfs_init_cinfo(struct nfs_commit_info *cinfo,
884 		    struct inode *inode,
885 		    struct nfs_direct_req *dreq)
886 {
887 	if (dreq)
888 		nfs_init_cinfo_from_dreq(cinfo, dreq);
889 	else
890 		nfs_init_cinfo_from_inode(cinfo, inode);
891 }
892 EXPORT_SYMBOL_GPL(nfs_init_cinfo);
893 
894 /*
895  * Add a request to the inode's commit list.
896  */
897 void
nfs_mark_request_commit(struct nfs_page * req,struct pnfs_layout_segment * lseg,struct nfs_commit_info * cinfo,u32 ds_commit_idx)898 nfs_mark_request_commit(struct nfs_page *req, struct pnfs_layout_segment *lseg,
899 			struct nfs_commit_info *cinfo, u32 ds_commit_idx)
900 {
901 	if (pnfs_mark_request_commit(req, lseg, cinfo, ds_commit_idx))
902 		return;
903 	nfs_request_add_commit_list(req, cinfo);
904 }
905 
nfs_folio_clear_commit(struct folio * folio)906 static void nfs_folio_clear_commit(struct folio *folio)
907 {
908 	if (folio) {
909 		long nr = folio_nr_pages(folio);
910 
911 		node_stat_mod_folio(folio, NR_WRITEBACK, -nr);
912 		wb_stat_mod(&inode_to_bdi(folio->mapping->host)->wb,
913 			    WB_WRITEBACK, -nr);
914 	}
915 }
916 
917 /* Called holding the request lock on @req */
nfs_clear_request_commit(struct nfs_commit_info * cinfo,struct nfs_page * req)918 static void nfs_clear_request_commit(struct nfs_commit_info *cinfo,
919 				     struct nfs_page *req)
920 {
921 	if (test_bit(PG_CLEAN, &req->wb_flags)) {
922 		struct nfs_open_context *ctx = nfs_req_openctx(req);
923 		struct inode *inode = d_inode(ctx->dentry);
924 
925 		mutex_lock(&NFS_I(inode)->commit_mutex);
926 		if (!pnfs_clear_request_commit(req, cinfo)) {
927 			nfs_request_remove_commit_list(req, cinfo);
928 		}
929 		mutex_unlock(&NFS_I(inode)->commit_mutex);
930 		nfs_folio_clear_commit(nfs_page_to_folio(req));
931 	}
932 }
933 
nfs_write_need_commit(struct nfs_pgio_header * hdr)934 int nfs_write_need_commit(struct nfs_pgio_header *hdr)
935 {
936 	if (hdr->verf.committed == NFS_DATA_SYNC)
937 		return hdr->lseg == NULL;
938 	return hdr->verf.committed != NFS_FILE_SYNC;
939 }
940 
nfs_async_write_init(struct nfs_pgio_header * hdr)941 static void nfs_async_write_init(struct nfs_pgio_header *hdr)
942 {
943 	nfs_io_completion_get(hdr->io_completion);
944 }
945 
nfs_write_completion(struct nfs_pgio_header * hdr)946 static void nfs_write_completion(struct nfs_pgio_header *hdr)
947 {
948 	struct nfs_commit_info cinfo;
949 	unsigned long bytes = 0;
950 
951 	if (test_bit(NFS_IOHDR_REDO, &hdr->flags))
952 		goto out;
953 	nfs_init_cinfo_from_inode(&cinfo, hdr->inode);
954 	while (!list_empty(&hdr->pages)) {
955 		struct nfs_page *req = nfs_list_entry(hdr->pages.next);
956 
957 		bytes += req->wb_bytes;
958 		nfs_list_remove_request(req);
959 		if (test_bit(NFS_IOHDR_ERROR, &hdr->flags) &&
960 		    (hdr->good_bytes < bytes)) {
961 			trace_nfs_comp_error(hdr->inode, req, hdr->error);
962 			nfs_mapping_set_error(nfs_page_to_folio(req),
963 					      hdr->error);
964 			goto remove_req;
965 		}
966 		if (nfs_write_need_commit(hdr)) {
967 			/* Reset wb_nio, since the write was successful. */
968 			req->wb_nio = 0;
969 			memcpy(&req->wb_verf, &hdr->verf.verifier, sizeof(req->wb_verf));
970 			nfs_mark_request_commit(req, hdr->lseg, &cinfo,
971 				hdr->pgio_mirror_idx);
972 			goto next;
973 		}
974 remove_req:
975 		nfs_inode_remove_request(req);
976 next:
977 		nfs_page_end_writeback(req);
978 		nfs_release_request(req);
979 	}
980 out:
981 	nfs_io_completion_put(hdr->io_completion);
982 	hdr->release(hdr);
983 }
984 
985 unsigned long
nfs_reqs_to_commit(struct nfs_commit_info * cinfo)986 nfs_reqs_to_commit(struct nfs_commit_info *cinfo)
987 {
988 	return atomic_long_read(&cinfo->mds->ncommit);
989 }
990 
991 /* NFS_I(cinfo->inode)->commit_mutex held by caller */
992 int
nfs_scan_commit_list(struct list_head * src,struct list_head * dst,struct nfs_commit_info * cinfo,int max)993 nfs_scan_commit_list(struct list_head *src, struct list_head *dst,
994 		     struct nfs_commit_info *cinfo, int max)
995 {
996 	struct nfs_page *req, *tmp;
997 	int ret = 0;
998 
999 	list_for_each_entry_safe(req, tmp, src, wb_list) {
1000 		kref_get(&req->wb_kref);
1001 		if (!nfs_lock_request(req)) {
1002 			nfs_release_request(req);
1003 			continue;
1004 		}
1005 		nfs_request_remove_commit_list(req, cinfo);
1006 		clear_bit(PG_COMMIT_TO_DS, &req->wb_flags);
1007 		nfs_list_add_request(req, dst);
1008 		ret++;
1009 		if ((ret == max) && !cinfo->dreq)
1010 			break;
1011 		cond_resched();
1012 	}
1013 	return ret;
1014 }
1015 EXPORT_SYMBOL_GPL(nfs_scan_commit_list);
1016 
1017 /*
1018  * nfs_scan_commit - Scan an inode for commit requests
1019  * @inode: NFS inode to scan
1020  * @dst: mds destination list
1021  * @cinfo: mds and ds lists of reqs ready to commit
1022  *
1023  * Moves requests from the inode's 'commit' request list.
1024  * The requests are *not* checked to ensure that they form a contiguous set.
1025  */
1026 int
nfs_scan_commit(struct inode * inode,struct list_head * dst,struct nfs_commit_info * cinfo)1027 nfs_scan_commit(struct inode *inode, struct list_head *dst,
1028 		struct nfs_commit_info *cinfo)
1029 {
1030 	int ret = 0;
1031 
1032 	if (!atomic_long_read(&cinfo->mds->ncommit))
1033 		return 0;
1034 	mutex_lock(&NFS_I(cinfo->inode)->commit_mutex);
1035 	if (atomic_long_read(&cinfo->mds->ncommit) > 0) {
1036 		const int max = INT_MAX;
1037 
1038 		ret = nfs_scan_commit_list(&cinfo->mds->list, dst,
1039 					   cinfo, max);
1040 		ret += pnfs_scan_commit_lists(inode, cinfo, max - ret);
1041 	}
1042 	mutex_unlock(&NFS_I(cinfo->inode)->commit_mutex);
1043 	return ret;
1044 }
1045 
1046 /*
1047  * Search for an existing write request, and attempt to update
1048  * it to reflect a new dirty region on a given page.
1049  *
1050  * If the attempt fails, then the existing request is flushed out
1051  * to disk.
1052  */
nfs_try_to_update_request(struct folio * folio,unsigned int offset,unsigned int bytes)1053 static struct nfs_page *nfs_try_to_update_request(struct folio *folio,
1054 						  unsigned int offset,
1055 						  unsigned int bytes)
1056 {
1057 	struct nfs_page *req;
1058 	unsigned int rqend;
1059 	unsigned int end;
1060 	int error;
1061 
1062 	end = offset + bytes;
1063 
1064 	req = nfs_lock_and_join_requests(folio);
1065 	if (IS_ERR_OR_NULL(req))
1066 		return req;
1067 
1068 	rqend = req->wb_offset + req->wb_bytes;
1069 	/*
1070 	 * Tell the caller to flush out the request if
1071 	 * the offsets are non-contiguous.
1072 	 * Note: nfs_flush_incompatible() will already
1073 	 * have flushed out requests having wrong owners.
1074 	 */
1075 	if (offset > rqend || end < req->wb_offset)
1076 		goto out_flushme;
1077 
1078 	/* Okay, the request matches. Update the region */
1079 	if (offset < req->wb_offset) {
1080 		req->wb_offset = offset;
1081 		req->wb_pgbase = offset;
1082 	}
1083 	if (end > rqend)
1084 		req->wb_bytes = end - req->wb_offset;
1085 	else
1086 		req->wb_bytes = rqend - req->wb_offset;
1087 	req->wb_nio = 0;
1088 	return req;
1089 out_flushme:
1090 	/*
1091 	 * Note: we mark the request dirty here because
1092 	 * nfs_lock_and_join_requests() cannot preserve
1093 	 * commit flags, so we have to replay the write.
1094 	 */
1095 	nfs_mark_request_dirty(req);
1096 	nfs_unlock_and_release_request(req);
1097 	error = nfs_wb_folio(folio->mapping->host, folio);
1098 	return (error < 0) ? ERR_PTR(error) : NULL;
1099 }
1100 
1101 /*
1102  * Try to update an existing write request, or create one if there is none.
1103  *
1104  * Note: Should always be called with the Page Lock held to prevent races
1105  * if we have to add a new request. Also assumes that the caller has
1106  * already called nfs_flush_incompatible() if necessary.
1107  */
nfs_setup_write_request(struct nfs_open_context * ctx,struct folio * folio,unsigned int offset,unsigned int bytes)1108 static struct nfs_page *nfs_setup_write_request(struct nfs_open_context *ctx,
1109 						struct folio *folio,
1110 						unsigned int offset,
1111 						unsigned int bytes)
1112 {
1113 	struct nfs_page *req;
1114 
1115 	req = nfs_try_to_update_request(folio, offset, bytes);
1116 	if (req != NULL)
1117 		goto out;
1118 	req = nfs_page_create_from_folio(ctx, folio, offset, bytes);
1119 	if (IS_ERR(req))
1120 		goto out;
1121 	nfs_inode_add_request(req);
1122 out:
1123 	return req;
1124 }
1125 
nfs_writepage_setup(struct nfs_open_context * ctx,struct folio * folio,unsigned int offset,unsigned int count)1126 static int nfs_writepage_setup(struct nfs_open_context *ctx,
1127 			       struct folio *folio, unsigned int offset,
1128 			       unsigned int count)
1129 {
1130 	struct nfs_page *req;
1131 
1132 	req = nfs_setup_write_request(ctx, folio, offset, count);
1133 	if (IS_ERR(req))
1134 		return PTR_ERR(req);
1135 	/* Update file length */
1136 	nfs_grow_file(folio, offset, count);
1137 	nfs_mark_uptodate(req);
1138 	nfs_mark_request_dirty(req);
1139 	nfs_unlock_and_release_request(req);
1140 	return 0;
1141 }
1142 
nfs_flush_incompatible(struct file * file,struct folio * folio)1143 int nfs_flush_incompatible(struct file *file, struct folio *folio)
1144 {
1145 	struct nfs_open_context *ctx = nfs_file_open_context(file);
1146 	struct nfs_lock_context *l_ctx;
1147 	struct file_lock_context *flctx = locks_inode_context(file_inode(file));
1148 	struct nfs_page	*req;
1149 	int do_flush, status;
1150 	/*
1151 	 * Look for a request corresponding to this page. If there
1152 	 * is one, and it belongs to another file, we flush it out
1153 	 * before we try to copy anything into the page. Do this
1154 	 * due to the lack of an ACCESS-type call in NFSv2.
1155 	 * Also do the same if we find a request from an existing
1156 	 * dropped page.
1157 	 */
1158 	do {
1159 		req = nfs_folio_find_head_request(folio);
1160 		if (req == NULL)
1161 			return 0;
1162 		l_ctx = req->wb_lock_context;
1163 		do_flush = nfs_page_to_folio(req) != folio ||
1164 			   !nfs_match_open_context(nfs_req_openctx(req), ctx);
1165 		if (l_ctx && flctx &&
1166 		    !(list_empty_careful(&flctx->flc_posix) &&
1167 		      list_empty_careful(&flctx->flc_flock))) {
1168 			do_flush |= l_ctx->lockowner != current->files;
1169 		}
1170 		nfs_release_request(req);
1171 		if (!do_flush)
1172 			return 0;
1173 		status = nfs_wb_folio(folio->mapping->host, folio);
1174 	} while (status == 0);
1175 	return status;
1176 }
1177 
1178 /*
1179  * Avoid buffered writes when a open context credential's key would
1180  * expire soon.
1181  *
1182  * Returns -EACCES if the key will expire within RPC_KEY_EXPIRE_FAIL.
1183  *
1184  * Return 0 and set a credential flag which triggers the inode to flush
1185  * and performs  NFS_FILE_SYNC writes if the key will expired within
1186  * RPC_KEY_EXPIRE_TIMEO.
1187  */
1188 int
nfs_key_timeout_notify(struct file * filp,struct inode * inode)1189 nfs_key_timeout_notify(struct file *filp, struct inode *inode)
1190 {
1191 	struct nfs_open_context *ctx = nfs_file_open_context(filp);
1192 
1193 	if (nfs_ctx_key_to_expire(ctx, inode) &&
1194 	    !rcu_access_pointer(ctx->ll_cred))
1195 		/* Already expired! */
1196 		return -EACCES;
1197 	return 0;
1198 }
1199 
1200 /*
1201  * Test if the open context credential key is marked to expire soon.
1202  */
nfs_ctx_key_to_expire(struct nfs_open_context * ctx,struct inode * inode)1203 bool nfs_ctx_key_to_expire(struct nfs_open_context *ctx, struct inode *inode)
1204 {
1205 	struct rpc_auth *auth = NFS_SERVER(inode)->client->cl_auth;
1206 	struct rpc_cred *cred, *new, *old = NULL;
1207 	struct auth_cred acred = {
1208 		.cred = ctx->cred,
1209 	};
1210 	bool ret = false;
1211 
1212 	rcu_read_lock();
1213 	cred = rcu_dereference(ctx->ll_cred);
1214 	if (cred && !(cred->cr_ops->crkey_timeout &&
1215 		      cred->cr_ops->crkey_timeout(cred)))
1216 		goto out;
1217 	rcu_read_unlock();
1218 
1219 	new = auth->au_ops->lookup_cred(auth, &acred, 0);
1220 	if (new == cred) {
1221 		put_rpccred(new);
1222 		return true;
1223 	}
1224 	if (IS_ERR_OR_NULL(new)) {
1225 		new = NULL;
1226 		ret = true;
1227 	} else if (new->cr_ops->crkey_timeout &&
1228 		   new->cr_ops->crkey_timeout(new))
1229 		ret = true;
1230 
1231 	rcu_read_lock();
1232 	old = rcu_dereference_protected(xchg(&ctx->ll_cred,
1233 					     RCU_INITIALIZER(new)), 1);
1234 out:
1235 	rcu_read_unlock();
1236 	put_rpccred(old);
1237 	return ret;
1238 }
1239 
1240 /*
1241  * If the page cache is marked as unsafe or invalid, then we can't rely on
1242  * the PageUptodate() flag. In this case, we will need to turn off
1243  * write optimisations that depend on the page contents being correct.
1244  */
nfs_folio_write_uptodate(struct folio * folio,unsigned int pagelen)1245 static bool nfs_folio_write_uptodate(struct folio *folio, unsigned int pagelen)
1246 {
1247 	struct inode *inode = folio->mapping->host;
1248 	struct nfs_inode *nfsi = NFS_I(inode);
1249 
1250 	if (nfs_have_delegated_attributes(inode))
1251 		goto out;
1252 	if (nfsi->cache_validity &
1253 	    (NFS_INO_INVALID_CHANGE | NFS_INO_INVALID_SIZE))
1254 		return false;
1255 	smp_rmb();
1256 	if (test_bit(NFS_INO_INVALIDATING, &nfsi->flags) && pagelen != 0)
1257 		return false;
1258 out:
1259 	if (nfsi->cache_validity & NFS_INO_INVALID_DATA && pagelen != 0)
1260 		return false;
1261 	return folio_test_uptodate(folio) != 0;
1262 }
1263 
1264 static bool
is_whole_file_wrlock(struct file_lock * fl)1265 is_whole_file_wrlock(struct file_lock *fl)
1266 {
1267 	return fl->fl_start == 0 && fl->fl_end == OFFSET_MAX &&
1268 			lock_is_write(fl);
1269 }
1270 
1271 /* If we know the page is up to date, and we're not using byte range locks (or
1272  * if we have the whole file locked for writing), it may be more efficient to
1273  * extend the write to cover the entire page in order to avoid fragmentation
1274  * inefficiencies.
1275  *
1276  * If the file is opened for synchronous writes then we can just skip the rest
1277  * of the checks.
1278  */
nfs_can_extend_write(struct file * file,struct folio * folio,unsigned int pagelen)1279 static int nfs_can_extend_write(struct file *file, struct folio *folio,
1280 				unsigned int pagelen)
1281 {
1282 	struct inode *inode = file_inode(file);
1283 	struct file_lock_context *flctx = locks_inode_context(inode);
1284 	struct file_lock *fl;
1285 	int ret;
1286 	unsigned int mntflags = NFS_SERVER(inode)->flags;
1287 
1288 	if (mntflags & NFS_MOUNT_NO_ALIGNWRITE)
1289 		return 0;
1290 	if (file->f_flags & O_DSYNC)
1291 		return 0;
1292 	if (!nfs_folio_write_uptodate(folio, pagelen))
1293 		return 0;
1294 	if (nfs_have_write_delegation(inode))
1295 		return 1;
1296 	if (!flctx || (list_empty_careful(&flctx->flc_flock) &&
1297 		       list_empty_careful(&flctx->flc_posix)))
1298 		return 1;
1299 
1300 	/* Check to see if there are whole file write locks */
1301 	ret = 0;
1302 	spin_lock(&flctx->flc_lock);
1303 	if (!list_empty(&flctx->flc_posix)) {
1304 		fl = list_first_entry(&flctx->flc_posix, struct file_lock,
1305 					c.flc_list);
1306 		if (is_whole_file_wrlock(fl))
1307 			ret = 1;
1308 	} else if (!list_empty(&flctx->flc_flock)) {
1309 		fl = list_first_entry(&flctx->flc_flock, struct file_lock,
1310 					c.flc_list);
1311 		if (lock_is_write(fl))
1312 			ret = 1;
1313 	}
1314 	spin_unlock(&flctx->flc_lock);
1315 	return ret;
1316 }
1317 
1318 /*
1319  * Update and possibly write a cached page of an NFS file.
1320  *
1321  * XXX: Keep an eye on generic_file_read to make sure it doesn't do bad
1322  * things with a page scheduled for an RPC call (e.g. invalidate it).
1323  */
nfs_update_folio(struct file * file,struct folio * folio,unsigned int offset,unsigned int count)1324 int nfs_update_folio(struct file *file, struct folio *folio,
1325 		     unsigned int offset, unsigned int count)
1326 {
1327 	struct nfs_open_context *ctx = nfs_file_open_context(file);
1328 	struct address_space *mapping = folio->mapping;
1329 	struct inode *inode = mapping->host;
1330 	unsigned int pagelen = nfs_folio_length(folio);
1331 	int		status = 0;
1332 
1333 	nfs_inc_stats(inode, NFSIOS_VFSUPDATEPAGE);
1334 
1335 	dprintk("NFS:       nfs_update_folio(%pD2 %d@%lld)\n", file, count,
1336 		(long long)(folio_pos(folio) + offset));
1337 
1338 	if (!count)
1339 		goto out;
1340 
1341 	if (nfs_can_extend_write(file, folio, pagelen)) {
1342 		unsigned int end = count + offset;
1343 
1344 		offset = round_down(offset, PAGE_SIZE);
1345 		if (end < pagelen)
1346 			end = min(round_up(end, PAGE_SIZE), pagelen);
1347 		count = end - offset;
1348 	}
1349 
1350 	status = nfs_writepage_setup(ctx, folio, offset, count);
1351 	if (status < 0)
1352 		nfs_set_pageerror(mapping);
1353 out:
1354 	dprintk("NFS:       nfs_update_folio returns %d (isize %lld)\n",
1355 			status, (long long)i_size_read(inode));
1356 	return status;
1357 }
1358 
flush_task_priority(int how)1359 static int flush_task_priority(int how)
1360 {
1361 	switch (how & (FLUSH_HIGHPRI|FLUSH_LOWPRI)) {
1362 		case FLUSH_HIGHPRI:
1363 			return RPC_PRIORITY_HIGH;
1364 		case FLUSH_LOWPRI:
1365 			return RPC_PRIORITY_LOW;
1366 	}
1367 	return RPC_PRIORITY_NORMAL;
1368 }
1369 
nfs_initiate_write(struct nfs_pgio_header * hdr,struct rpc_message * msg,const struct nfs_rpc_ops * rpc_ops,struct rpc_task_setup * task_setup_data,int how)1370 static void nfs_initiate_write(struct nfs_pgio_header *hdr,
1371 			       struct rpc_message *msg,
1372 			       const struct nfs_rpc_ops *rpc_ops,
1373 			       struct rpc_task_setup *task_setup_data, int how)
1374 {
1375 	int priority = flush_task_priority(how);
1376 
1377 	if (IS_SWAPFILE(hdr->inode))
1378 		task_setup_data->flags |= RPC_TASK_SWAPPER;
1379 	task_setup_data->priority = priority;
1380 	rpc_ops->write_setup(hdr, msg, &task_setup_data->rpc_client);
1381 	trace_nfs_initiate_write(hdr);
1382 }
1383 
1384 /* If a nfs_flush_* function fails, it should remove reqs from @head and
1385  * call this on each, which will prepare them to be retried on next
1386  * writeback using standard nfs.
1387  */
nfs_redirty_request(struct nfs_page * req)1388 static void nfs_redirty_request(struct nfs_page *req)
1389 {
1390 	struct nfs_inode *nfsi = NFS_I(nfs_page_to_inode(req));
1391 
1392 	/* Bump the transmission count */
1393 	req->wb_nio++;
1394 	nfs_mark_request_dirty(req);
1395 	atomic_long_inc(&nfsi->redirtied_pages);
1396 	nfs_page_end_writeback(req);
1397 	nfs_release_request(req);
1398 }
1399 
nfs_async_write_error(struct list_head * head,int error)1400 static void nfs_async_write_error(struct list_head *head, int error)
1401 {
1402 	struct nfs_page	*req;
1403 
1404 	while (!list_empty(head)) {
1405 		req = nfs_list_entry(head->next);
1406 		nfs_list_remove_request(req);
1407 		if (nfs_error_is_fatal_on_server(error))
1408 			nfs_write_error(req, error);
1409 		else
1410 			nfs_redirty_request(req);
1411 	}
1412 }
1413 
nfs_async_write_reschedule_io(struct nfs_pgio_header * hdr)1414 static void nfs_async_write_reschedule_io(struct nfs_pgio_header *hdr)
1415 {
1416 	nfs_async_write_error(&hdr->pages, 0);
1417 }
1418 
1419 static const struct nfs_pgio_completion_ops nfs_async_write_completion_ops = {
1420 	.init_hdr = nfs_async_write_init,
1421 	.error_cleanup = nfs_async_write_error,
1422 	.completion = nfs_write_completion,
1423 	.reschedule_io = nfs_async_write_reschedule_io,
1424 };
1425 
nfs_pageio_init_write(struct nfs_pageio_descriptor * pgio,struct inode * inode,int ioflags,bool force_mds,const struct nfs_pgio_completion_ops * compl_ops)1426 void nfs_pageio_init_write(struct nfs_pageio_descriptor *pgio,
1427 			       struct inode *inode, int ioflags, bool force_mds,
1428 			       const struct nfs_pgio_completion_ops *compl_ops)
1429 {
1430 	struct nfs_server *server = NFS_SERVER(inode);
1431 	const struct nfs_pageio_ops *pg_ops = &nfs_pgio_rw_ops;
1432 
1433 #ifdef CONFIG_NFS_V4_1
1434 	if (server->pnfs_curr_ld && !force_mds)
1435 		pg_ops = server->pnfs_curr_ld->pg_write_ops;
1436 #endif
1437 	nfs_pageio_init(pgio, inode, pg_ops, compl_ops, &nfs_rw_write_ops,
1438 			server->wsize, ioflags);
1439 }
1440 EXPORT_SYMBOL_GPL(nfs_pageio_init_write);
1441 
nfs_pageio_reset_write_mds(struct nfs_pageio_descriptor * pgio)1442 void nfs_pageio_reset_write_mds(struct nfs_pageio_descriptor *pgio)
1443 {
1444 	struct nfs_pgio_mirror *mirror;
1445 
1446 	if (pgio->pg_ops && pgio->pg_ops->pg_cleanup)
1447 		pgio->pg_ops->pg_cleanup(pgio);
1448 
1449 	pgio->pg_ops = &nfs_pgio_rw_ops;
1450 
1451 	nfs_pageio_stop_mirroring(pgio);
1452 
1453 	mirror = &pgio->pg_mirrors[0];
1454 	mirror->pg_bsize = NFS_SERVER(pgio->pg_inode)->wsize;
1455 }
1456 EXPORT_SYMBOL_GPL(nfs_pageio_reset_write_mds);
1457 
1458 
nfs_commit_prepare(struct rpc_task * task,void * calldata)1459 void nfs_commit_prepare(struct rpc_task *task, void *calldata)
1460 {
1461 	struct nfs_commit_data *data = calldata;
1462 
1463 	NFS_PROTO(data->inode)->commit_rpc_prepare(task, data);
1464 }
1465 
nfs_writeback_check_extend(struct nfs_pgio_header * hdr,struct nfs_fattr * fattr)1466 static void nfs_writeback_check_extend(struct nfs_pgio_header *hdr,
1467 		struct nfs_fattr *fattr)
1468 {
1469 	struct nfs_pgio_args *argp = &hdr->args;
1470 	struct nfs_pgio_res *resp = &hdr->res;
1471 	u64 size = argp->offset + resp->count;
1472 
1473 	if (!(fattr->valid & NFS_ATTR_FATTR_SIZE))
1474 		fattr->size = size;
1475 	if (nfs_size_to_loff_t(fattr->size) < i_size_read(hdr->inode)) {
1476 		fattr->valid &= ~NFS_ATTR_FATTR_SIZE;
1477 		return;
1478 	}
1479 	if (size != fattr->size)
1480 		return;
1481 	/* Set attribute barrier */
1482 	nfs_fattr_set_barrier(fattr);
1483 	/* ...and update size */
1484 	fattr->valid |= NFS_ATTR_FATTR_SIZE;
1485 }
1486 
nfs_writeback_update_inode(struct nfs_pgio_header * hdr)1487 void nfs_writeback_update_inode(struct nfs_pgio_header *hdr)
1488 {
1489 	struct nfs_fattr *fattr = &hdr->fattr;
1490 	struct inode *inode = hdr->inode;
1491 
1492 	if (nfs_have_delegated_mtime(inode)) {
1493 		spin_lock(&inode->i_lock);
1494 		nfs_set_cache_invalid(inode, NFS_INO_INVALID_BLOCKS);
1495 		spin_unlock(&inode->i_lock);
1496 		return;
1497 	}
1498 
1499 	spin_lock(&inode->i_lock);
1500 	nfs_writeback_check_extend(hdr, fattr);
1501 	nfs_post_op_update_inode_force_wcc_locked(inode, fattr);
1502 	spin_unlock(&inode->i_lock);
1503 }
1504 EXPORT_SYMBOL_GPL(nfs_writeback_update_inode);
1505 
1506 /*
1507  * This function is called when the WRITE call is complete.
1508  */
nfs_writeback_done(struct rpc_task * task,struct nfs_pgio_header * hdr,struct inode * inode)1509 static int nfs_writeback_done(struct rpc_task *task,
1510 			      struct nfs_pgio_header *hdr,
1511 			      struct inode *inode)
1512 {
1513 	int status;
1514 
1515 	/*
1516 	 * ->write_done will attempt to use post-op attributes to detect
1517 	 * conflicting writes by other clients.  A strict interpretation
1518 	 * of close-to-open would allow us to continue caching even if
1519 	 * another writer had changed the file, but some applications
1520 	 * depend on tighter cache coherency when writing.
1521 	 */
1522 	status = NFS_PROTO(inode)->write_done(task, hdr);
1523 	if (status != 0)
1524 		return status;
1525 
1526 	nfs_add_stats(inode, NFSIOS_SERVERWRITTENBYTES, hdr->res.count);
1527 	trace_nfs_writeback_done(task, hdr);
1528 
1529 	if (task->tk_status >= 0) {
1530 		enum nfs3_stable_how committed = hdr->res.verf->committed;
1531 
1532 		if (committed == NFS_UNSTABLE) {
1533 			/*
1534 			 * We have some uncommitted data on the server at
1535 			 * this point, so ensure that we keep track of that
1536 			 * fact irrespective of what later writes do.
1537 			 */
1538 			set_bit(NFS_IOHDR_UNSTABLE_WRITES, &hdr->flags);
1539 		}
1540 
1541 		if (committed < hdr->args.stable) {
1542 			/* We tried a write call, but the server did not
1543 			 * commit data to stable storage even though we
1544 			 * requested it.
1545 			 * Note: There is a known bug in Tru64 < 5.0 in which
1546 			 *	 the server reports NFS_DATA_SYNC, but performs
1547 			 *	 NFS_FILE_SYNC. We therefore implement this checking
1548 			 *	 as a dprintk() in order to avoid filling syslog.
1549 			 */
1550 			static unsigned long    complain;
1551 
1552 			/* Note this will print the MDS for a DS write */
1553 			if (time_before(complain, jiffies)) {
1554 				dprintk("NFS:       faulty NFS server %s:"
1555 					" (committed = %d) != (stable = %d)\n",
1556 					NFS_SERVER(inode)->nfs_client->cl_hostname,
1557 					committed, hdr->args.stable);
1558 				complain = jiffies + 300 * HZ;
1559 			}
1560 		}
1561 	}
1562 
1563 	/* Deal with the suid/sgid bit corner case */
1564 	if (nfs_should_remove_suid(inode)) {
1565 		spin_lock(&inode->i_lock);
1566 		nfs_set_cache_invalid(inode, NFS_INO_INVALID_MODE);
1567 		spin_unlock(&inode->i_lock);
1568 	}
1569 	return 0;
1570 }
1571 
1572 /*
1573  * This function is called when the WRITE call is complete.
1574  */
nfs_writeback_result(struct rpc_task * task,struct nfs_pgio_header * hdr)1575 static void nfs_writeback_result(struct rpc_task *task,
1576 				 struct nfs_pgio_header *hdr)
1577 {
1578 	struct nfs_pgio_args	*argp = &hdr->args;
1579 	struct nfs_pgio_res	*resp = &hdr->res;
1580 
1581 	if (resp->count < argp->count) {
1582 		static unsigned long    complain;
1583 
1584 		/* This a short write! */
1585 		nfs_inc_stats(hdr->inode, NFSIOS_SHORTWRITE);
1586 
1587 		/* Has the server at least made some progress? */
1588 		if (resp->count == 0) {
1589 			if (time_before(complain, jiffies)) {
1590 				printk(KERN_WARNING
1591 				       "NFS: Server wrote zero bytes, expected %u.\n",
1592 				       argp->count);
1593 				complain = jiffies + 300 * HZ;
1594 			}
1595 			nfs_set_pgio_error(hdr, -EIO, argp->offset);
1596 			task->tk_status = -EIO;
1597 			return;
1598 		}
1599 
1600 		/* For non rpc-based layout drivers, retry-through-MDS */
1601 		if (!task->tk_ops) {
1602 			hdr->pnfs_error = -EAGAIN;
1603 			return;
1604 		}
1605 
1606 		/* Was this an NFSv2 write or an NFSv3 stable write? */
1607 		if (resp->verf->committed != NFS_UNSTABLE) {
1608 			/* Resend from where the server left off */
1609 			hdr->mds_offset += resp->count;
1610 			argp->offset += resp->count;
1611 			argp->pgbase += resp->count;
1612 			argp->count -= resp->count;
1613 		} else {
1614 			/* Resend as a stable write in order to avoid
1615 			 * headaches in the case of a server crash.
1616 			 */
1617 			argp->stable = NFS_FILE_SYNC;
1618 		}
1619 		resp->count = 0;
1620 		resp->verf->committed = 0;
1621 		rpc_restart_call_prepare(task);
1622 	}
1623 }
1624 
wait_on_commit(struct nfs_mds_commit_info * cinfo)1625 static int wait_on_commit(struct nfs_mds_commit_info *cinfo)
1626 {
1627 	return wait_var_event_killable(&cinfo->rpcs_out,
1628 				       !atomic_read(&cinfo->rpcs_out));
1629 }
1630 
nfs_commit_begin(struct nfs_mds_commit_info * cinfo)1631 void nfs_commit_begin(struct nfs_mds_commit_info *cinfo)
1632 {
1633 	atomic_inc(&cinfo->rpcs_out);
1634 }
1635 
nfs_commit_end(struct nfs_mds_commit_info * cinfo)1636 bool nfs_commit_end(struct nfs_mds_commit_info *cinfo)
1637 {
1638 	if (atomic_dec_and_test(&cinfo->rpcs_out)) {
1639 		wake_up_var(&cinfo->rpcs_out);
1640 		return true;
1641 	}
1642 	return false;
1643 }
1644 
nfs_commitdata_release(struct nfs_commit_data * data)1645 void nfs_commitdata_release(struct nfs_commit_data *data)
1646 {
1647 	put_nfs_open_context(data->context);
1648 	nfs_commit_free(data);
1649 }
1650 EXPORT_SYMBOL_GPL(nfs_commitdata_release);
1651 
nfs_initiate_commit(struct rpc_clnt * clnt,struct nfs_commit_data * data,const struct nfs_rpc_ops * nfs_ops,const struct rpc_call_ops * call_ops,int how,int flags,struct nfsd_file * localio)1652 int nfs_initiate_commit(struct rpc_clnt *clnt, struct nfs_commit_data *data,
1653 			const struct nfs_rpc_ops *nfs_ops,
1654 			const struct rpc_call_ops *call_ops,
1655 			int how, int flags,
1656 			struct nfsd_file *localio)
1657 {
1658 	struct rpc_task *task;
1659 	int priority = flush_task_priority(how);
1660 	struct rpc_message msg = {
1661 		.rpc_argp = &data->args,
1662 		.rpc_resp = &data->res,
1663 		.rpc_cred = data->cred,
1664 	};
1665 	struct rpc_task_setup task_setup_data = {
1666 		.task = &data->task,
1667 		.rpc_client = clnt,
1668 		.rpc_message = &msg,
1669 		.callback_ops = call_ops,
1670 		.callback_data = data,
1671 		.workqueue = nfsiod_workqueue,
1672 		.flags = RPC_TASK_ASYNC | flags,
1673 		.priority = priority,
1674 	};
1675 
1676 	if (nfs_server_capable(data->inode, NFS_CAP_MOVEABLE))
1677 		task_setup_data.flags |= RPC_TASK_MOVEABLE;
1678 
1679 	/* Set up the initial task struct.  */
1680 	nfs_ops->commit_setup(data, &msg, &task_setup_data.rpc_client);
1681 	trace_nfs_initiate_commit(data);
1682 
1683 	dprintk("NFS: initiated commit call\n");
1684 
1685 	if (localio)
1686 		return nfs_local_commit(localio, data, call_ops, how);
1687 
1688 	task = rpc_run_task(&task_setup_data);
1689 	if (IS_ERR(task))
1690 		return PTR_ERR(task);
1691 	if (how & FLUSH_SYNC)
1692 		rpc_wait_for_completion_task(task);
1693 	rpc_put_task(task);
1694 	return 0;
1695 }
1696 EXPORT_SYMBOL_GPL(nfs_initiate_commit);
1697 
nfs_get_lwb(struct list_head * head)1698 static loff_t nfs_get_lwb(struct list_head *head)
1699 {
1700 	loff_t lwb = 0;
1701 	struct nfs_page *req;
1702 
1703 	list_for_each_entry(req, head, wb_list)
1704 		if (lwb < (req_offset(req) + req->wb_bytes))
1705 			lwb = req_offset(req) + req->wb_bytes;
1706 
1707 	return lwb;
1708 }
1709 
1710 /*
1711  * Set up the argument/result storage required for the RPC call.
1712  */
nfs_init_commit(struct nfs_commit_data * data,struct list_head * head,struct pnfs_layout_segment * lseg,struct nfs_commit_info * cinfo)1713 void nfs_init_commit(struct nfs_commit_data *data,
1714 		     struct list_head *head,
1715 		     struct pnfs_layout_segment *lseg,
1716 		     struct nfs_commit_info *cinfo)
1717 {
1718 	struct nfs_page *first;
1719 	struct nfs_open_context *ctx;
1720 	struct inode *inode;
1721 
1722 	/* Set up the RPC argument and reply structs
1723 	 * NB: take care not to mess about with data->commit et al. */
1724 
1725 	if (head)
1726 		list_splice_init(head, &data->pages);
1727 
1728 	first = nfs_list_entry(data->pages.next);
1729 	ctx = nfs_req_openctx(first);
1730 	inode = d_inode(ctx->dentry);
1731 
1732 	data->inode	  = inode;
1733 	data->cred	  = ctx->cred;
1734 	data->lseg	  = lseg; /* reference transferred */
1735 	/* only set lwb for pnfs commit */
1736 	if (lseg)
1737 		data->lwb = nfs_get_lwb(&data->pages);
1738 	data->mds_ops     = &nfs_commit_ops;
1739 	data->completion_ops = cinfo->completion_ops;
1740 	data->dreq	  = cinfo->dreq;
1741 
1742 	data->args.fh     = NFS_FH(data->inode);
1743 	/* Note: we always request a commit of the entire inode */
1744 	data->args.offset = 0;
1745 	data->args.count  = 0;
1746 	data->context     = get_nfs_open_context(ctx);
1747 	data->res.fattr   = &data->fattr;
1748 	data->res.verf    = &data->verf;
1749 	nfs_fattr_init(&data->fattr);
1750 	nfs_commit_begin(cinfo->mds);
1751 }
1752 EXPORT_SYMBOL_GPL(nfs_init_commit);
1753 
nfs_retry_commit(struct list_head * page_list,struct pnfs_layout_segment * lseg,struct nfs_commit_info * cinfo,u32 ds_commit_idx)1754 void nfs_retry_commit(struct list_head *page_list,
1755 		      struct pnfs_layout_segment *lseg,
1756 		      struct nfs_commit_info *cinfo,
1757 		      u32 ds_commit_idx)
1758 {
1759 	struct nfs_page *req;
1760 
1761 	while (!list_empty(page_list)) {
1762 		req = nfs_list_entry(page_list->next);
1763 		nfs_list_remove_request(req);
1764 		nfs_mark_request_commit(req, lseg, cinfo, ds_commit_idx);
1765 		nfs_folio_clear_commit(nfs_page_to_folio(req));
1766 		nfs_unlock_and_release_request(req);
1767 	}
1768 }
1769 EXPORT_SYMBOL_GPL(nfs_retry_commit);
1770 
nfs_commit_resched_write(struct nfs_commit_info * cinfo,struct nfs_page * req)1771 static void nfs_commit_resched_write(struct nfs_commit_info *cinfo,
1772 				     struct nfs_page *req)
1773 {
1774 	struct folio *folio = nfs_page_to_folio(req);
1775 
1776 	filemap_dirty_folio(folio_mapping(folio), folio);
1777 }
1778 
1779 /*
1780  * Commit dirty pages
1781  */
1782 static int
nfs_commit_list(struct inode * inode,struct list_head * head,int how,struct nfs_commit_info * cinfo)1783 nfs_commit_list(struct inode *inode, struct list_head *head, int how,
1784 		struct nfs_commit_info *cinfo)
1785 {
1786 	struct nfs_commit_data	*data;
1787 	struct nfsd_file *localio;
1788 	unsigned short task_flags = 0;
1789 
1790 	/* another commit raced with us */
1791 	if (list_empty(head))
1792 		return 0;
1793 
1794 	data = nfs_commitdata_alloc();
1795 	if (!data) {
1796 		nfs_retry_commit(head, NULL, cinfo, -1);
1797 		return -ENOMEM;
1798 	}
1799 
1800 	/* Set up the argument struct */
1801 	nfs_init_commit(data, head, NULL, cinfo);
1802 	if (NFS_SERVER(inode)->nfs_client->cl_minorversion)
1803 		task_flags = RPC_TASK_MOVEABLE;
1804 
1805 	localio = nfs_local_open_fh(NFS_SERVER(inode)->nfs_client, data->cred,
1806 				    data->args.fh, &data->context->nfl,
1807 				    data->context->mode);
1808 	return nfs_initiate_commit(NFS_CLIENT(inode), data, NFS_PROTO(inode),
1809 				   data->mds_ops, how,
1810 				   RPC_TASK_CRED_NOREF | task_flags, localio);
1811 }
1812 
1813 /*
1814  * COMMIT call returned
1815  */
nfs_commit_done(struct rpc_task * task,void * calldata)1816 static void nfs_commit_done(struct rpc_task *task, void *calldata)
1817 {
1818 	struct nfs_commit_data	*data = calldata;
1819 
1820 	/* Call the NFS version-specific code */
1821 	NFS_PROTO(data->inode)->commit_done(task, data);
1822 	trace_nfs_commit_done(task, data);
1823 }
1824 
nfs_commit_release_pages(struct nfs_commit_data * data)1825 static void nfs_commit_release_pages(struct nfs_commit_data *data)
1826 {
1827 	const struct nfs_writeverf *verf = data->res.verf;
1828 	struct nfs_page	*req;
1829 	int status = data->task.tk_status;
1830 	struct nfs_commit_info cinfo;
1831 	struct folio *folio;
1832 
1833 	while (!list_empty(&data->pages)) {
1834 		req = nfs_list_entry(data->pages.next);
1835 		nfs_list_remove_request(req);
1836 		folio = nfs_page_to_folio(req);
1837 		nfs_folio_clear_commit(folio);
1838 
1839 		dprintk("NFS:       commit (%s/%llu %d@%lld)",
1840 			nfs_req_openctx(req)->dentry->d_sb->s_id,
1841 			(unsigned long long)NFS_FILEID(d_inode(nfs_req_openctx(req)->dentry)),
1842 			req->wb_bytes,
1843 			(long long)req_offset(req));
1844 		if (status < 0) {
1845 			if (folio) {
1846 				trace_nfs_commit_error(data->inode, req,
1847 						       status);
1848 				nfs_mapping_set_error(folio, status);
1849 				nfs_inode_remove_request(req);
1850 			}
1851 			dprintk_cont(", error = %d\n", status);
1852 			goto next;
1853 		}
1854 
1855 		/* Okay, COMMIT succeeded, apparently. Check the verifier
1856 		 * returned by the server against all stored verfs. */
1857 		if (nfs_write_match_verf(verf, req)) {
1858 			/* We have a match */
1859 			if (folio)
1860 				nfs_inode_remove_request(req);
1861 			dprintk_cont(" OK\n");
1862 			goto next;
1863 		}
1864 		/* We have a mismatch. Write the page again */
1865 		dprintk_cont(" mismatch\n");
1866 		nfs_mark_request_dirty(req);
1867 		atomic_long_inc(&NFS_I(data->inode)->redirtied_pages);
1868 	next:
1869 		nfs_unlock_and_release_request(req);
1870 		/* Latency breaker */
1871 		cond_resched();
1872 	}
1873 
1874 	nfs_init_cinfo(&cinfo, data->inode, data->dreq);
1875 	nfs_commit_end(cinfo.mds);
1876 }
1877 
nfs_commit_release(void * calldata)1878 static void nfs_commit_release(void *calldata)
1879 {
1880 	struct nfs_commit_data *data = calldata;
1881 
1882 	data->completion_ops->completion(data);
1883 	nfs_commitdata_release(calldata);
1884 }
1885 
1886 static const struct rpc_call_ops nfs_commit_ops = {
1887 	.rpc_call_prepare = nfs_commit_prepare,
1888 	.rpc_call_done = nfs_commit_done,
1889 	.rpc_release = nfs_commit_release,
1890 };
1891 
1892 static const struct nfs_commit_completion_ops nfs_commit_completion_ops = {
1893 	.completion = nfs_commit_release_pages,
1894 	.resched_write = nfs_commit_resched_write,
1895 };
1896 
nfs_generic_commit_list(struct inode * inode,struct list_head * head,int how,struct nfs_commit_info * cinfo)1897 int nfs_generic_commit_list(struct inode *inode, struct list_head *head,
1898 			    int how, struct nfs_commit_info *cinfo)
1899 {
1900 	int status;
1901 
1902 	status = pnfs_commit_list(inode, head, how, cinfo);
1903 	if (status == PNFS_NOT_ATTEMPTED)
1904 		status = nfs_commit_list(inode, head, how, cinfo);
1905 	return status;
1906 }
1907 
__nfs_commit_inode(struct inode * inode,int how,struct writeback_control * wbc)1908 static int __nfs_commit_inode(struct inode *inode, int how,
1909 		struct writeback_control *wbc)
1910 {
1911 	LIST_HEAD(head);
1912 	struct nfs_commit_info cinfo;
1913 	int may_wait = how & FLUSH_SYNC;
1914 	int ret, nscan;
1915 
1916 	how &= ~FLUSH_SYNC;
1917 	nfs_init_cinfo_from_inode(&cinfo, inode);
1918 	nfs_commit_begin(cinfo.mds);
1919 	for (;;) {
1920 		ret = nscan = nfs_scan_commit(inode, &head, &cinfo);
1921 		if (ret <= 0)
1922 			break;
1923 		ret = nfs_generic_commit_list(inode, &head, how, &cinfo);
1924 		if (ret < 0)
1925 			break;
1926 		ret = 0;
1927 		if (wbc && wbc->sync_mode == WB_SYNC_NONE) {
1928 			if (nscan < wbc->nr_to_write)
1929 				wbc->nr_to_write -= nscan;
1930 			else
1931 				wbc->nr_to_write = 0;
1932 		}
1933 		if (nscan < INT_MAX)
1934 			break;
1935 		cond_resched();
1936 	}
1937 	nfs_commit_end(cinfo.mds);
1938 	if (ret || !may_wait)
1939 		return ret;
1940 	return wait_on_commit(cinfo.mds);
1941 }
1942 
nfs_commit_inode(struct inode * inode,int how)1943 int nfs_commit_inode(struct inode *inode, int how)
1944 {
1945 	return __nfs_commit_inode(inode, how, NULL);
1946 }
1947 EXPORT_SYMBOL_GPL(nfs_commit_inode);
1948 
nfs_write_inode(struct inode * inode,struct writeback_control * wbc)1949 int nfs_write_inode(struct inode *inode, struct writeback_control *wbc)
1950 {
1951 	struct nfs_inode *nfsi = NFS_I(inode);
1952 	int flags = FLUSH_SYNC;
1953 	int ret = 0;
1954 
1955 	if (wbc->sync_mode == WB_SYNC_NONE) {
1956 		/* no commits means nothing needs to be done */
1957 		if (!atomic_long_read(&nfsi->commit_info.ncommit))
1958 			goto check_requests_outstanding;
1959 
1960 		/* Don't commit yet if this is a non-blocking flush and there
1961 		 * are a lot of outstanding writes for this mapping.
1962 		 */
1963 		if (mapping_tagged(inode->i_mapping, PAGECACHE_TAG_WRITEBACK))
1964 			goto out_mark_dirty;
1965 
1966 		/* don't wait for the COMMIT response */
1967 		flags = 0;
1968 	}
1969 
1970 	ret = __nfs_commit_inode(inode, flags, wbc);
1971 	if (!ret) {
1972 		if (flags & FLUSH_SYNC)
1973 			return 0;
1974 	} else if (atomic_long_read(&nfsi->commit_info.ncommit))
1975 		goto out_mark_dirty;
1976 
1977 check_requests_outstanding:
1978 	if (!atomic_read(&nfsi->commit_info.rpcs_out))
1979 		return ret;
1980 out_mark_dirty:
1981 	__mark_inode_dirty(inode, I_DIRTY_DATASYNC);
1982 	return ret;
1983 }
1984 EXPORT_SYMBOL_GPL(nfs_write_inode);
1985 
1986 /*
1987  * Wrapper for filemap_write_and_wait_range()
1988  *
1989  * Needed for pNFS in order to ensure data becomes visible to the
1990  * client.
1991  */
nfs_filemap_write_and_wait_range(struct address_space * mapping,loff_t lstart,loff_t lend)1992 int nfs_filemap_write_and_wait_range(struct address_space *mapping,
1993 		loff_t lstart, loff_t lend)
1994 {
1995 	int ret;
1996 
1997 	ret = filemap_write_and_wait_range(mapping, lstart, lend);
1998 	if (ret == 0)
1999 		ret = pnfs_sync_inode(mapping->host, true);
2000 	return ret;
2001 }
2002 EXPORT_SYMBOL_GPL(nfs_filemap_write_and_wait_range);
2003 
2004 /*
2005  * flush the inode to disk.
2006  */
nfs_wb_all(struct inode * inode)2007 int nfs_wb_all(struct inode *inode)
2008 {
2009 	int ret;
2010 
2011 	trace_nfs_writeback_inode_enter(inode);
2012 
2013 	ret = filemap_write_and_wait(inode->i_mapping);
2014 	if (ret)
2015 		goto out;
2016 	ret = nfs_commit_inode(inode, FLUSH_SYNC);
2017 	if (ret < 0)
2018 		goto out;
2019 	pnfs_sync_inode(inode, true);
2020 	ret = 0;
2021 
2022 out:
2023 	trace_nfs_writeback_inode_exit(inode, ret);
2024 	return ret;
2025 }
2026 EXPORT_SYMBOL_GPL(nfs_wb_all);
2027 
nfs_wb_folio_cancel(struct inode * inode,struct folio * folio)2028 int nfs_wb_folio_cancel(struct inode *inode, struct folio *folio)
2029 {
2030 	struct nfs_page *req;
2031 	int ret = 0;
2032 
2033 	folio_wait_writeback(folio);
2034 
2035 	/* blocking call to cancel all requests and join to a single (head)
2036 	 * request */
2037 	req = nfs_lock_and_join_requests(folio);
2038 
2039 	if (IS_ERR(req)) {
2040 		ret = PTR_ERR(req);
2041 	} else if (req) {
2042 		/* all requests from this folio have been cancelled by
2043 		 * nfs_lock_and_join_requests, so just remove the head
2044 		 * request from the inode / page_private pointer and
2045 		 * release it */
2046 		nfs_inode_remove_request(req);
2047 		nfs_unlock_and_release_request(req);
2048 	}
2049 
2050 	return ret;
2051 }
2052 
2053 /**
2054  * nfs_wb_folio - Write back all requests on one page
2055  * @inode: pointer to page
2056  * @folio: pointer to folio
2057  *
2058  * Assumes that the folio has been locked by the caller, and will
2059  * not unlock it.
2060  */
nfs_wb_folio(struct inode * inode,struct folio * folio)2061 int nfs_wb_folio(struct inode *inode, struct folio *folio)
2062 {
2063 	loff_t range_start = folio_pos(folio);
2064 	size_t len = folio_size(folio);
2065 	struct writeback_control wbc = {
2066 		.sync_mode = WB_SYNC_ALL,
2067 		.nr_to_write = 0,
2068 		.range_start = range_start,
2069 		.range_end = range_start + len - 1,
2070 	};
2071 	int ret;
2072 
2073 	trace_nfs_writeback_folio(inode, range_start, len);
2074 
2075 	for (;;) {
2076 		folio_wait_writeback(folio);
2077 		if (folio_clear_dirty_for_io(folio)) {
2078 			ret = nfs_writepage_locked(folio, &wbc);
2079 			if (ret < 0)
2080 				goto out_error;
2081 			continue;
2082 		}
2083 		ret = 0;
2084 		if (!folio_test_private(folio))
2085 			break;
2086 		ret = nfs_commit_inode(inode, FLUSH_SYNC);
2087 		if (ret < 0)
2088 			goto out_error;
2089 	}
2090 out_error:
2091 	trace_nfs_writeback_folio_done(inode, range_start, len, ret);
2092 	return ret;
2093 }
2094 
2095 #ifdef CONFIG_MIGRATION
nfs_migrate_folio(struct address_space * mapping,struct folio * dst,struct folio * src,enum migrate_mode mode)2096 int nfs_migrate_folio(struct address_space *mapping, struct folio *dst,
2097 		struct folio *src, enum migrate_mode mode)
2098 {
2099 	/*
2100 	 * If the private flag is set, the folio is currently associated with
2101 	 * an in-progress read or write request. Don't try to migrate it.
2102 	 *
2103 	 * FIXME: we could do this in principle, but we'll need a way to ensure
2104 	 *        that we can safely release the inode reference while holding
2105 	 *        the folio lock.
2106 	 */
2107 	if (folio_test_private(src)) {
2108 		if (mode == MIGRATE_SYNC)
2109 			nfs_wb_folio(src->mapping->host, src);
2110 		if (folio_test_private(src))
2111 			return -EBUSY;
2112 	}
2113 
2114 	if (folio_test_private_2(src)) { /* [DEPRECATED] */
2115 		if (mode == MIGRATE_ASYNC)
2116 			return -EBUSY;
2117 		folio_wait_private_2(src);
2118 	}
2119 
2120 	return migrate_folio(mapping, dst, src, mode);
2121 }
2122 #endif
2123 
nfs_init_writepagecache(void)2124 int __init nfs_init_writepagecache(void)
2125 {
2126 	nfs_wdata_cachep = kmem_cache_create("nfs_write_data",
2127 					     sizeof(struct nfs_pgio_header),
2128 					     0, SLAB_HWCACHE_ALIGN,
2129 					     NULL);
2130 	if (nfs_wdata_cachep == NULL)
2131 		return -ENOMEM;
2132 
2133 	nfs_wdata_mempool = mempool_create_slab_pool(MIN_POOL_WRITE,
2134 						     nfs_wdata_cachep);
2135 	if (nfs_wdata_mempool == NULL)
2136 		goto out_destroy_write_cache;
2137 
2138 	nfs_cdata_cachep = kmem_cache_create("nfs_commit_data",
2139 					     sizeof(struct nfs_commit_data),
2140 					     0, SLAB_HWCACHE_ALIGN,
2141 					     NULL);
2142 	if (nfs_cdata_cachep == NULL)
2143 		goto out_destroy_write_mempool;
2144 
2145 	nfs_commit_mempool = mempool_create_slab_pool(MIN_POOL_COMMIT,
2146 						      nfs_cdata_cachep);
2147 	if (nfs_commit_mempool == NULL)
2148 		goto out_destroy_commit_cache;
2149 
2150 	/*
2151 	 * NFS congestion size, scale with available memory.
2152 	 *
2153 	 *  64MB:    8192k
2154 	 * 128MB:   11585k
2155 	 * 256MB:   16384k
2156 	 * 512MB:   23170k
2157 	 *   1GB:   32768k
2158 	 *   2GB:   46340k
2159 	 *   4GB:   65536k
2160 	 *   8GB:   92681k
2161 	 *  16GB:  131072k
2162 	 *
2163 	 * This allows larger machines to have larger/more transfers.
2164 	 * Limit the default to 256M
2165 	 */
2166 	nfs_congestion_kb = (16*int_sqrt(totalram_pages())) << (PAGE_SHIFT-10);
2167 	if (nfs_congestion_kb > 256*1024)
2168 		nfs_congestion_kb = 256*1024;
2169 
2170 	return 0;
2171 
2172 out_destroy_commit_cache:
2173 	kmem_cache_destroy(nfs_cdata_cachep);
2174 out_destroy_write_mempool:
2175 	mempool_destroy(nfs_wdata_mempool);
2176 out_destroy_write_cache:
2177 	kmem_cache_destroy(nfs_wdata_cachep);
2178 	return -ENOMEM;
2179 }
2180 
nfs_destroy_writepagecache(void)2181 void nfs_destroy_writepagecache(void)
2182 {
2183 	mempool_destroy(nfs_commit_mempool);
2184 	kmem_cache_destroy(nfs_cdata_cachep);
2185 	mempool_destroy(nfs_wdata_mempool);
2186 	kmem_cache_destroy(nfs_wdata_cachep);
2187 }
2188 
2189 static const struct nfs_rw_ops nfs_rw_write_ops = {
2190 	.rw_alloc_header	= nfs_writehdr_alloc,
2191 	.rw_free_header		= nfs_writehdr_free,
2192 	.rw_done		= nfs_writeback_done,
2193 	.rw_result		= nfs_writeback_result,
2194 	.rw_initiate		= nfs_initiate_write,
2195 };
2196