NFS: remove NFS_PAGE_TAG_LOCKED
[linux-2.6.git] / fs / nfs / write.c
1 /*
2  * linux/fs/nfs/write.c
3  *
4  * Write file data over NFS.
5  *
6  * Copyright (C) 1996, 1997, Olaf Kirch <okir@monad.swb.de>
7  */
8
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/mm.h>
12 #include <linux/pagemap.h>
13 #include <linux/file.h>
14 #include <linux/writeback.h>
15 #include <linux/swap.h>
16 #include <linux/migrate.h>
17
18 #include <linux/sunrpc/clnt.h>
19 #include <linux/nfs_fs.h>
20 #include <linux/nfs_mount.h>
21 #include <linux/nfs_page.h>
22 #include <linux/backing-dev.h>
23 #include <linux/export.h>
24
25 #include <asm/uaccess.h>
26
27 #include "delegation.h"
28 #include "internal.h"
29 #include "iostat.h"
30 #include "nfs4_fs.h"
31 #include "fscache.h"
32 #include "pnfs.h"
33
34 #define NFSDBG_FACILITY         NFSDBG_PAGECACHE
35
36 #define MIN_POOL_WRITE          (32)
37 #define MIN_POOL_COMMIT         (4)
38
39 /*
40  * Local function declarations
41  */
42 static void nfs_pageio_init_write(struct nfs_pageio_descriptor *desc,
43                                   struct inode *inode, int ioflags);
44 static void nfs_redirty_request(struct nfs_page *req);
45 static const struct rpc_call_ops nfs_write_partial_ops;
46 static const struct rpc_call_ops nfs_write_full_ops;
47 static const struct rpc_call_ops nfs_commit_ops;
48
49 static struct kmem_cache *nfs_wdata_cachep;
50 static mempool_t *nfs_wdata_mempool;
51 static mempool_t *nfs_commit_mempool;
52
53 struct nfs_write_data *nfs_commitdata_alloc(void)
54 {
55         struct nfs_write_data *p = mempool_alloc(nfs_commit_mempool, GFP_NOFS);
56
57         if (p) {
58                 memset(p, 0, sizeof(*p));
59                 INIT_LIST_HEAD(&p->pages);
60         }
61         return p;
62 }
63 EXPORT_SYMBOL_GPL(nfs_commitdata_alloc);
64
65 void nfs_commit_free(struct nfs_write_data *p)
66 {
67         if (p && (p->pagevec != &p->page_array[0]))
68                 kfree(p->pagevec);
69         mempool_free(p, nfs_commit_mempool);
70 }
71 EXPORT_SYMBOL_GPL(nfs_commit_free);
72
73 struct nfs_write_data *nfs_writedata_alloc(unsigned int pagecount)
74 {
75         struct nfs_write_data *p = mempool_alloc(nfs_wdata_mempool, GFP_NOFS);
76
77         if (p) {
78                 memset(p, 0, sizeof(*p));
79                 INIT_LIST_HEAD(&p->pages);
80                 p->npages = pagecount;
81                 if (pagecount <= ARRAY_SIZE(p->page_array))
82                         p->pagevec = p->page_array;
83                 else {
84                         p->pagevec = kcalloc(pagecount, sizeof(struct page *), GFP_NOFS);
85                         if (!p->pagevec) {
86                                 mempool_free(p, nfs_wdata_mempool);
87                                 p = NULL;
88                         }
89                 }
90         }
91         return p;
92 }
93
94 void nfs_writedata_free(struct nfs_write_data *p)
95 {
96         if (p && (p->pagevec != &p->page_array[0]))
97                 kfree(p->pagevec);
98         mempool_free(p, nfs_wdata_mempool);
99 }
100
101 void nfs_writedata_release(struct nfs_write_data *wdata)
102 {
103         put_lseg(wdata->lseg);
104         put_nfs_open_context(wdata->args.context);
105         nfs_writedata_free(wdata);
106 }
107
108 static void nfs_context_set_write_error(struct nfs_open_context *ctx, int error)
109 {
110         ctx->error = error;
111         smp_wmb();
112         set_bit(NFS_CONTEXT_ERROR_WRITE, &ctx->flags);
113 }
114
115 static struct nfs_page *nfs_page_find_request_locked(struct page *page)
116 {
117         struct nfs_page *req = NULL;
118
119         if (PagePrivate(page)) {
120                 req = (struct nfs_page *)page_private(page);
121                 if (req != NULL)
122                         kref_get(&req->wb_kref);
123         }
124         return req;
125 }
126
127 static struct nfs_page *nfs_page_find_request(struct page *page)
128 {
129         struct inode *inode = page->mapping->host;
130         struct nfs_page *req = NULL;
131
132         spin_lock(&inode->i_lock);
133         req = nfs_page_find_request_locked(page);
134         spin_unlock(&inode->i_lock);
135         return req;
136 }
137
138 /* Adjust the file length if we're writing beyond the end */
139 static void nfs_grow_file(struct page *page, unsigned int offset, unsigned int count)
140 {
141         struct inode *inode = page->mapping->host;
142         loff_t end, i_size;
143         pgoff_t end_index;
144
145         spin_lock(&inode->i_lock);
146         i_size = i_size_read(inode);
147         end_index = (i_size - 1) >> PAGE_CACHE_SHIFT;
148         if (i_size > 0 && page->index < end_index)
149                 goto out;
150         end = ((loff_t)page->index << PAGE_CACHE_SHIFT) + ((loff_t)offset+count);
151         if (i_size >= end)
152                 goto out;
153         i_size_write(inode, end);
154         nfs_inc_stats(inode, NFSIOS_EXTENDWRITE);
155 out:
156         spin_unlock(&inode->i_lock);
157 }
158
159 /* A writeback failed: mark the page as bad, and invalidate the page cache */
160 static void nfs_set_pageerror(struct page *page)
161 {
162         SetPageError(page);
163         nfs_zap_mapping(page->mapping->host, page->mapping);
164 }
165
166 /* We can set the PG_uptodate flag if we see that a write request
167  * covers the full page.
168  */
169 static void nfs_mark_uptodate(struct page *page, unsigned int base, unsigned int count)
170 {
171         if (PageUptodate(page))
172                 return;
173         if (base != 0)
174                 return;
175         if (count != nfs_page_length(page))
176                 return;
177         SetPageUptodate(page);
178 }
179
180 static int wb_priority(struct writeback_control *wbc)
181 {
182         if (wbc->for_reclaim)
183                 return FLUSH_HIGHPRI | FLUSH_STABLE;
184         if (wbc->for_kupdate || wbc->for_background)
185                 return FLUSH_LOWPRI | FLUSH_COND_STABLE;
186         return FLUSH_COND_STABLE;
187 }
188
189 /*
190  * NFS congestion control
191  */
192
193 int nfs_congestion_kb;
194
195 #define NFS_CONGESTION_ON_THRESH        (nfs_congestion_kb >> (PAGE_SHIFT-10))
196 #define NFS_CONGESTION_OFF_THRESH       \
197         (NFS_CONGESTION_ON_THRESH - (NFS_CONGESTION_ON_THRESH >> 2))
198
199 static int nfs_set_page_writeback(struct page *page)
200 {
201         int ret = test_set_page_writeback(page);
202
203         if (!ret) {
204                 struct inode *inode = page->mapping->host;
205                 struct nfs_server *nfss = NFS_SERVER(inode);
206
207                 page_cache_get(page);
208                 if (atomic_long_inc_return(&nfss->writeback) >
209                                 NFS_CONGESTION_ON_THRESH) {
210                         set_bdi_congested(&nfss->backing_dev_info,
211                                                 BLK_RW_ASYNC);
212                 }
213         }
214         return ret;
215 }
216
217 static void nfs_end_page_writeback(struct page *page)
218 {
219         struct inode *inode = page->mapping->host;
220         struct nfs_server *nfss = NFS_SERVER(inode);
221
222         end_page_writeback(page);
223         page_cache_release(page);
224         if (atomic_long_dec_return(&nfss->writeback) < NFS_CONGESTION_OFF_THRESH)
225                 clear_bdi_congested(&nfss->backing_dev_info, BLK_RW_ASYNC);
226 }
227
228 static struct nfs_page *nfs_find_and_lock_request(struct page *page, bool nonblock)
229 {
230         struct inode *inode = page->mapping->host;
231         struct nfs_page *req;
232         int ret;
233
234         spin_lock(&inode->i_lock);
235         for (;;) {
236                 req = nfs_page_find_request_locked(page);
237                 if (req == NULL)
238                         break;
239                 if (nfs_lock_request_dontget(req))
240                         break;
241                 /* Note: If we hold the page lock, as is the case in nfs_writepage,
242                  *       then the call to nfs_lock_request_dontget() will always
243                  *       succeed provided that someone hasn't already marked the
244                  *       request as dirty (in which case we don't care).
245                  */
246                 spin_unlock(&inode->i_lock);
247                 if (!nonblock)
248                         ret = nfs_wait_on_request(req);
249                 else
250                         ret = -EAGAIN;
251                 nfs_release_request(req);
252                 if (ret != 0)
253                         return ERR_PTR(ret);
254                 spin_lock(&inode->i_lock);
255         }
256         spin_unlock(&inode->i_lock);
257         return req;
258 }
259
260 /*
261  * Find an associated nfs write request, and prepare to flush it out
262  * May return an error if the user signalled nfs_wait_on_request().
263  */
264 static int nfs_page_async_flush(struct nfs_pageio_descriptor *pgio,
265                                 struct page *page, bool nonblock)
266 {
267         struct nfs_page *req;
268         int ret = 0;
269
270         req = nfs_find_and_lock_request(page, nonblock);
271         if (!req)
272                 goto out;
273         ret = PTR_ERR(req);
274         if (IS_ERR(req))
275                 goto out;
276
277         ret = nfs_set_page_writeback(page);
278         BUG_ON(ret != 0);
279         BUG_ON(test_bit(PG_CLEAN, &req->wb_flags));
280
281         if (!nfs_pageio_add_request(pgio, req)) {
282                 nfs_redirty_request(req);
283                 ret = pgio->pg_error;
284         }
285 out:
286         return ret;
287 }
288
289 static int nfs_do_writepage(struct page *page, struct writeback_control *wbc, struct nfs_pageio_descriptor *pgio)
290 {
291         struct inode *inode = page->mapping->host;
292         int ret;
293
294         nfs_inc_stats(inode, NFSIOS_VFSWRITEPAGE);
295         nfs_add_stats(inode, NFSIOS_WRITEPAGES, 1);
296
297         nfs_pageio_cond_complete(pgio, page->index);
298         ret = nfs_page_async_flush(pgio, page, wbc->sync_mode == WB_SYNC_NONE);
299         if (ret == -EAGAIN) {
300                 redirty_page_for_writepage(wbc, page);
301                 ret = 0;
302         }
303         return ret;
304 }
305
306 /*
307  * Write an mmapped page to the server.
308  */
309 static int nfs_writepage_locked(struct page *page, struct writeback_control *wbc)
310 {
311         struct nfs_pageio_descriptor pgio;
312         int err;
313
314         nfs_pageio_init_write(&pgio, page->mapping->host, wb_priority(wbc));
315         err = nfs_do_writepage(page, wbc, &pgio);
316         nfs_pageio_complete(&pgio);
317         if (err < 0)
318                 return err;
319         if (pgio.pg_error < 0)
320                 return pgio.pg_error;
321         return 0;
322 }
323
324 int nfs_writepage(struct page *page, struct writeback_control *wbc)
325 {
326         int ret;
327
328         ret = nfs_writepage_locked(page, wbc);
329         unlock_page(page);
330         return ret;
331 }
332
333 static int nfs_writepages_callback(struct page *page, struct writeback_control *wbc, void *data)
334 {
335         int ret;
336
337         ret = nfs_do_writepage(page, wbc, data);
338         unlock_page(page);
339         return ret;
340 }
341
342 int nfs_writepages(struct address_space *mapping, struct writeback_control *wbc)
343 {
344         struct inode *inode = mapping->host;
345         unsigned long *bitlock = &NFS_I(inode)->flags;
346         struct nfs_pageio_descriptor pgio;
347         int err;
348
349         /* Stop dirtying of new pages while we sync */
350         err = wait_on_bit_lock(bitlock, NFS_INO_FLUSHING,
351                         nfs_wait_bit_killable, TASK_KILLABLE);
352         if (err)
353                 goto out_err;
354
355         nfs_inc_stats(inode, NFSIOS_VFSWRITEPAGES);
356
357         nfs_pageio_init_write(&pgio, inode, wb_priority(wbc));
358         err = write_cache_pages(mapping, wbc, nfs_writepages_callback, &pgio);
359         nfs_pageio_complete(&pgio);
360
361         clear_bit_unlock(NFS_INO_FLUSHING, bitlock);
362         smp_mb__after_clear_bit();
363         wake_up_bit(bitlock, NFS_INO_FLUSHING);
364
365         if (err < 0)
366                 goto out_err;
367         err = pgio.pg_error;
368         if (err < 0)
369                 goto out_err;
370         return 0;
371 out_err:
372         return err;
373 }
374
375 /*
376  * Insert a write request into an inode
377  */
378 static int nfs_inode_add_request(struct inode *inode, struct nfs_page *req)
379 {
380         struct nfs_inode *nfsi = NFS_I(inode);
381         int error;
382
383         error = radix_tree_preload(GFP_NOFS);
384         if (error != 0)
385                 goto out;
386
387         /* Lock the request! */
388         nfs_lock_request_dontget(req);
389
390         spin_lock(&inode->i_lock);
391         error = radix_tree_insert(&nfsi->nfs_page_tree, req->wb_index, req);
392         BUG_ON(error);
393         if (!nfsi->npages && nfs_have_delegation(inode, FMODE_WRITE))
394                 inode->i_version++;
395         set_bit(PG_MAPPED, &req->wb_flags);
396         SetPagePrivate(req->wb_page);
397         set_page_private(req->wb_page, (unsigned long)req);
398         nfsi->npages++;
399         kref_get(&req->wb_kref);
400         spin_unlock(&inode->i_lock);
401         radix_tree_preload_end();
402 out:
403         return error;
404 }
405
406 /*
407  * Remove a write request from an inode
408  */
409 static void nfs_inode_remove_request(struct nfs_page *req)
410 {
411         struct inode *inode = req->wb_context->dentry->d_inode;
412         struct nfs_inode *nfsi = NFS_I(inode);
413
414         BUG_ON (!NFS_WBACK_BUSY(req));
415
416         spin_lock(&inode->i_lock);
417         set_page_private(req->wb_page, 0);
418         ClearPagePrivate(req->wb_page);
419         clear_bit(PG_MAPPED, &req->wb_flags);
420         radix_tree_delete(&nfsi->nfs_page_tree, req->wb_index);
421         nfsi->npages--;
422         spin_unlock(&inode->i_lock);
423         nfs_release_request(req);
424 }
425
426 static void
427 nfs_mark_request_dirty(struct nfs_page *req)
428 {
429         __set_page_dirty_nobuffers(req->wb_page);
430 }
431
432 #if defined(CONFIG_NFS_V3) || defined(CONFIG_NFS_V4)
433 /*
434  * Add a request to the inode's commit list.
435  */
436 static void
437 nfs_mark_request_commit(struct nfs_page *req, struct pnfs_layout_segment *lseg)
438 {
439         struct inode *inode = req->wb_context->dentry->d_inode;
440         struct nfs_inode *nfsi = NFS_I(inode);
441
442         spin_lock(&inode->i_lock);
443         set_bit(PG_CLEAN, &(req)->wb_flags);
444         radix_tree_tag_set(&nfsi->nfs_page_tree,
445                         req->wb_index,
446                         NFS_PAGE_TAG_COMMIT);
447         nfsi->ncommit++;
448         spin_unlock(&inode->i_lock);
449         pnfs_mark_request_commit(req, lseg);
450         inc_zone_page_state(req->wb_page, NR_UNSTABLE_NFS);
451         inc_bdi_stat(req->wb_page->mapping->backing_dev_info, BDI_RECLAIMABLE);
452         __mark_inode_dirty(inode, I_DIRTY_DATASYNC);
453 }
454
455 static int
456 nfs_clear_request_commit(struct nfs_page *req)
457 {
458         struct page *page = req->wb_page;
459
460         if (test_and_clear_bit(PG_CLEAN, &(req)->wb_flags)) {
461                 dec_zone_page_state(page, NR_UNSTABLE_NFS);
462                 dec_bdi_stat(page->mapping->backing_dev_info, BDI_RECLAIMABLE);
463                 return 1;
464         }
465         return 0;
466 }
467
468 static inline
469 int nfs_write_need_commit(struct nfs_write_data *data)
470 {
471         if (data->verf.committed == NFS_DATA_SYNC)
472                 return data->lseg == NULL;
473         else
474                 return data->verf.committed != NFS_FILE_SYNC;
475 }
476
477 static inline
478 int nfs_reschedule_unstable_write(struct nfs_page *req,
479                                   struct nfs_write_data *data)
480 {
481         if (test_and_clear_bit(PG_NEED_COMMIT, &req->wb_flags)) {
482                 nfs_mark_request_commit(req, data->lseg);
483                 return 1;
484         }
485         if (test_and_clear_bit(PG_NEED_RESCHED, &req->wb_flags)) {
486                 nfs_mark_request_dirty(req);
487                 return 1;
488         }
489         return 0;
490 }
491 #else
492 static inline void
493 nfs_mark_request_commit(struct nfs_page *req, struct pnfs_layout_segment *lseg)
494 {
495 }
496
497 static inline int
498 nfs_clear_request_commit(struct nfs_page *req)
499 {
500         return 0;
501 }
502
503 static inline
504 int nfs_write_need_commit(struct nfs_write_data *data)
505 {
506         return 0;
507 }
508
509 static inline
510 int nfs_reschedule_unstable_write(struct nfs_page *req,
511                                   struct nfs_write_data *data)
512 {
513         return 0;
514 }
515 #endif
516
517 #if defined(CONFIG_NFS_V3) || defined(CONFIG_NFS_V4)
518 static int
519 nfs_need_commit(struct nfs_inode *nfsi)
520 {
521         return radix_tree_tagged(&nfsi->nfs_page_tree, NFS_PAGE_TAG_COMMIT);
522 }
523
524 /*
525  * nfs_scan_commit - Scan an inode for commit requests
526  * @inode: NFS inode to scan
527  * @dst: destination list
528  * @idx_start: lower bound of page->index to scan.
529  * @npages: idx_start + npages sets the upper bound to scan.
530  *
531  * Moves requests from the inode's 'commit' request list.
532  * The requests are *not* checked to ensure that they form a contiguous set.
533  */
534 static int
535 nfs_scan_commit(struct inode *inode, struct list_head *dst, pgoff_t idx_start, unsigned int npages)
536 {
537         struct nfs_inode *nfsi = NFS_I(inode);
538         int ret;
539
540         if (!nfs_need_commit(nfsi))
541                 return 0;
542
543         spin_lock(&inode->i_lock);
544         ret = nfs_scan_list(nfsi, dst, idx_start, npages, NFS_PAGE_TAG_COMMIT);
545         if (ret > 0)
546                 nfsi->ncommit -= ret;
547         spin_unlock(&inode->i_lock);
548
549         if (nfs_need_commit(NFS_I(inode)))
550                 __mark_inode_dirty(inode, I_DIRTY_DATASYNC);
551
552         return ret;
553 }
554 #else
555 static inline int nfs_need_commit(struct nfs_inode *nfsi)
556 {
557         return 0;
558 }
559
560 static inline int nfs_scan_commit(struct inode *inode, struct list_head *dst, pgoff_t idx_start, unsigned int npages)
561 {
562         return 0;
563 }
564 #endif
565
566 /*
567  * Search for an existing write request, and attempt to update
568  * it to reflect a new dirty region on a given page.
569  *
570  * If the attempt fails, then the existing request is flushed out
571  * to disk.
572  */
573 static struct nfs_page *nfs_try_to_update_request(struct inode *inode,
574                 struct page *page,
575                 unsigned int offset,
576                 unsigned int bytes)
577 {
578         struct nfs_page *req;
579         unsigned int rqend;
580         unsigned int end;
581         int error;
582
583         if (!PagePrivate(page))
584                 return NULL;
585
586         end = offset + bytes;
587         spin_lock(&inode->i_lock);
588
589         for (;;) {
590                 req = nfs_page_find_request_locked(page);
591                 if (req == NULL)
592                         goto out_unlock;
593
594                 rqend = req->wb_offset + req->wb_bytes;
595                 /*
596                  * Tell the caller to flush out the request if
597                  * the offsets are non-contiguous.
598                  * Note: nfs_flush_incompatible() will already
599                  * have flushed out requests having wrong owners.
600                  */
601                 if (offset > rqend
602                     || end < req->wb_offset)
603                         goto out_flushme;
604
605                 if (nfs_lock_request_dontget(req))
606                         break;
607
608                 /* The request is locked, so wait and then retry */
609                 spin_unlock(&inode->i_lock);
610                 error = nfs_wait_on_request(req);
611                 nfs_release_request(req);
612                 if (error != 0)
613                         goto out_err;
614                 spin_lock(&inode->i_lock);
615         }
616
617         if (nfs_clear_request_commit(req) &&
618             radix_tree_tag_clear(&NFS_I(inode)->nfs_page_tree,
619                                  req->wb_index, NFS_PAGE_TAG_COMMIT) != NULL) {
620                 NFS_I(inode)->ncommit--;
621                 pnfs_clear_request_commit(req);
622         }
623
624         /* Okay, the request matches. Update the region */
625         if (offset < req->wb_offset) {
626                 req->wb_offset = offset;
627                 req->wb_pgbase = offset;
628         }
629         if (end > rqend)
630                 req->wb_bytes = end - req->wb_offset;
631         else
632                 req->wb_bytes = rqend - req->wb_offset;
633 out_unlock:
634         spin_unlock(&inode->i_lock);
635         return req;
636 out_flushme:
637         spin_unlock(&inode->i_lock);
638         nfs_release_request(req);
639         error = nfs_wb_page(inode, page);
640 out_err:
641         return ERR_PTR(error);
642 }
643
644 /*
645  * Try to update an existing write request, or create one if there is none.
646  *
647  * Note: Should always be called with the Page Lock held to prevent races
648  * if we have to add a new request. Also assumes that the caller has
649  * already called nfs_flush_incompatible() if necessary.
650  */
651 static struct nfs_page * nfs_setup_write_request(struct nfs_open_context* ctx,
652                 struct page *page, unsigned int offset, unsigned int bytes)
653 {
654         struct inode *inode = page->mapping->host;
655         struct nfs_page *req;
656         int error;
657
658         req = nfs_try_to_update_request(inode, page, offset, bytes);
659         if (req != NULL)
660                 goto out;
661         req = nfs_create_request(ctx, inode, page, offset, bytes);
662         if (IS_ERR(req))
663                 goto out;
664         error = nfs_inode_add_request(inode, req);
665         if (error != 0) {
666                 nfs_release_request(req);
667                 req = ERR_PTR(error);
668         }
669 out:
670         return req;
671 }
672
673 static int nfs_writepage_setup(struct nfs_open_context *ctx, struct page *page,
674                 unsigned int offset, unsigned int count)
675 {
676         struct nfs_page *req;
677
678         req = nfs_setup_write_request(ctx, page, offset, count);
679         if (IS_ERR(req))
680                 return PTR_ERR(req);
681         /* Update file length */
682         nfs_grow_file(page, offset, count);
683         nfs_mark_uptodate(page, req->wb_pgbase, req->wb_bytes);
684         nfs_mark_request_dirty(req);
685         nfs_unlock_request(req);
686         return 0;
687 }
688
689 int nfs_flush_incompatible(struct file *file, struct page *page)
690 {
691         struct nfs_open_context *ctx = nfs_file_open_context(file);
692         struct nfs_page *req;
693         int do_flush, status;
694         /*
695          * Look for a request corresponding to this page. If there
696          * is one, and it belongs to another file, we flush it out
697          * before we try to copy anything into the page. Do this
698          * due to the lack of an ACCESS-type call in NFSv2.
699          * Also do the same if we find a request from an existing
700          * dropped page.
701          */
702         do {
703                 req = nfs_page_find_request(page);
704                 if (req == NULL)
705                         return 0;
706                 do_flush = req->wb_page != page || req->wb_context != ctx ||
707                         req->wb_lock_context->lockowner != current->files ||
708                         req->wb_lock_context->pid != current->tgid;
709                 nfs_release_request(req);
710                 if (!do_flush)
711                         return 0;
712                 status = nfs_wb_page(page->mapping->host, page);
713         } while (status == 0);
714         return status;
715 }
716
717 /*
718  * If the page cache is marked as unsafe or invalid, then we can't rely on
719  * the PageUptodate() flag. In this case, we will need to turn off
720  * write optimisations that depend on the page contents being correct.
721  */
722 static int nfs_write_pageuptodate(struct page *page, struct inode *inode)
723 {
724         return PageUptodate(page) &&
725                 !(NFS_I(inode)->cache_validity & (NFS_INO_REVAL_PAGECACHE|NFS_INO_INVALID_DATA));
726 }
727
728 /*
729  * Update and possibly write a cached page of an NFS file.
730  *
731  * XXX: Keep an eye on generic_file_read to make sure it doesn't do bad
732  * things with a page scheduled for an RPC call (e.g. invalidate it).
733  */
734 int nfs_updatepage(struct file *file, struct page *page,
735                 unsigned int offset, unsigned int count)
736 {
737         struct nfs_open_context *ctx = nfs_file_open_context(file);
738         struct inode    *inode = page->mapping->host;
739         int             status = 0;
740
741         nfs_inc_stats(inode, NFSIOS_VFSUPDATEPAGE);
742
743         dprintk("NFS:       nfs_updatepage(%s/%s %d@%lld)\n",
744                 file->f_path.dentry->d_parent->d_name.name,
745                 file->f_path.dentry->d_name.name, count,
746                 (long long)(page_offset(page) + offset));
747
748         /* If we're not using byte range locks, and we know the page
749          * is up to date, it may be more efficient to extend the write
750          * to cover the entire page in order to avoid fragmentation
751          * inefficiencies.
752          */
753         if (nfs_write_pageuptodate(page, inode) &&
754                         inode->i_flock == NULL &&
755                         !(file->f_flags & O_DSYNC)) {
756                 count = max(count + offset, nfs_page_length(page));
757                 offset = 0;
758         }
759
760         status = nfs_writepage_setup(ctx, page, offset, count);
761         if (status < 0)
762                 nfs_set_pageerror(page);
763         else
764                 __set_page_dirty_nobuffers(page);
765
766         dprintk("NFS:       nfs_updatepage returns %d (isize %lld)\n",
767                         status, (long long)i_size_read(inode));
768         return status;
769 }
770
771 static void nfs_writepage_release(struct nfs_page *req,
772                                   struct nfs_write_data *data)
773 {
774         struct page *page = req->wb_page;
775
776         if (PageError(req->wb_page) || !nfs_reschedule_unstable_write(req, data))
777                 nfs_inode_remove_request(req);
778         nfs_unlock_request(req);
779         nfs_end_page_writeback(page);
780 }
781
782 static int flush_task_priority(int how)
783 {
784         switch (how & (FLUSH_HIGHPRI|FLUSH_LOWPRI)) {
785                 case FLUSH_HIGHPRI:
786                         return RPC_PRIORITY_HIGH;
787                 case FLUSH_LOWPRI:
788                         return RPC_PRIORITY_LOW;
789         }
790         return RPC_PRIORITY_NORMAL;
791 }
792
793 int nfs_initiate_write(struct nfs_write_data *data,
794                        struct rpc_clnt *clnt,
795                        const struct rpc_call_ops *call_ops,
796                        int how)
797 {
798         struct inode *inode = data->inode;
799         int priority = flush_task_priority(how);
800         struct rpc_task *task;
801         struct rpc_message msg = {
802                 .rpc_argp = &data->args,
803                 .rpc_resp = &data->res,
804                 .rpc_cred = data->cred,
805         };
806         struct rpc_task_setup task_setup_data = {
807                 .rpc_client = clnt,
808                 .task = &data->task,
809                 .rpc_message = &msg,
810                 .callback_ops = call_ops,
811                 .callback_data = data,
812                 .workqueue = nfsiod_workqueue,
813                 .flags = RPC_TASK_ASYNC,
814                 .priority = priority,
815         };
816         int ret = 0;
817
818         /* Set up the initial task struct.  */
819         NFS_PROTO(inode)->write_setup(data, &msg);
820
821         dprintk("NFS: %5u initiated write call "
822                 "(req %s/%lld, %u bytes @ offset %llu)\n",
823                 data->task.tk_pid,
824                 inode->i_sb->s_id,
825                 (long long)NFS_FILEID(inode),
826                 data->args.count,
827                 (unsigned long long)data->args.offset);
828
829         task = rpc_run_task(&task_setup_data);
830         if (IS_ERR(task)) {
831                 ret = PTR_ERR(task);
832                 goto out;
833         }
834         if (how & FLUSH_SYNC) {
835                 ret = rpc_wait_for_completion_task(task);
836                 if (ret == 0)
837                         ret = task->tk_status;
838         }
839         rpc_put_task(task);
840 out:
841         return ret;
842 }
843 EXPORT_SYMBOL_GPL(nfs_initiate_write);
844
845 /*
846  * Set up the argument/result storage required for the RPC call.
847  */
848 static void nfs_write_rpcsetup(struct nfs_page *req,
849                 struct nfs_write_data *data,
850                 unsigned int count, unsigned int offset,
851                 int how)
852 {
853         struct inode *inode = req->wb_context->dentry->d_inode;
854
855         /* Set up the RPC argument and reply structs
856          * NB: take care not to mess about with data->commit et al. */
857
858         data->req = req;
859         data->inode = inode = req->wb_context->dentry->d_inode;
860         data->cred = req->wb_context->cred;
861
862         data->args.fh     = NFS_FH(inode);
863         data->args.offset = req_offset(req) + offset;
864         /* pnfs_set_layoutcommit needs this */
865         data->mds_offset = data->args.offset;
866         data->args.pgbase = req->wb_pgbase + offset;
867         data->args.pages  = data->pagevec;
868         data->args.count  = count;
869         data->args.context = get_nfs_open_context(req->wb_context);
870         data->args.lock_context = req->wb_lock_context;
871         data->args.stable  = NFS_UNSTABLE;
872         switch (how & (FLUSH_STABLE | FLUSH_COND_STABLE)) {
873         case 0:
874                 break;
875         case FLUSH_COND_STABLE:
876                 if (nfs_need_commit(NFS_I(inode)))
877                         break;
878         default:
879                 data->args.stable = NFS_FILE_SYNC;
880         }
881
882         data->res.fattr   = &data->fattr;
883         data->res.count   = count;
884         data->res.verf    = &data->verf;
885         nfs_fattr_init(&data->fattr);
886 }
887
888 static int nfs_do_write(struct nfs_write_data *data,
889                 const struct rpc_call_ops *call_ops,
890                 int how)
891 {
892         struct inode *inode = data->args.context->dentry->d_inode;
893
894         return nfs_initiate_write(data, NFS_CLIENT(inode), call_ops, how);
895 }
896
897 static int nfs_do_multiple_writes(struct list_head *head,
898                 const struct rpc_call_ops *call_ops,
899                 int how)
900 {
901         struct nfs_write_data *data;
902         int ret = 0;
903
904         while (!list_empty(head)) {
905                 int ret2;
906
907                 data = list_entry(head->next, struct nfs_write_data, list);
908                 list_del_init(&data->list);
909                 
910                 ret2 = nfs_do_write(data, call_ops, how);
911                  if (ret == 0)
912                          ret = ret2;
913         }
914         return ret;
915 }
916
917 /* If a nfs_flush_* function fails, it should remove reqs from @head and
918  * call this on each, which will prepare them to be retried on next
919  * writeback using standard nfs.
920  */
921 static void nfs_redirty_request(struct nfs_page *req)
922 {
923         struct page *page = req->wb_page;
924
925         nfs_mark_request_dirty(req);
926         nfs_unlock_request(req);
927         nfs_end_page_writeback(page);
928 }
929
930 /*
931  * Generate multiple small requests to write out a single
932  * contiguous dirty area on one page.
933  */
934 static int nfs_flush_multi(struct nfs_pageio_descriptor *desc, struct list_head *res)
935 {
936         struct nfs_page *req = nfs_list_entry(desc->pg_list.next);
937         struct page *page = req->wb_page;
938         struct nfs_write_data *data;
939         size_t wsize = desc->pg_bsize, nbytes;
940         unsigned int offset;
941         int requests = 0;
942         int ret = 0;
943
944         nfs_list_remove_request(req);
945
946         if ((desc->pg_ioflags & FLUSH_COND_STABLE) &&
947             (desc->pg_moreio || NFS_I(desc->pg_inode)->ncommit ||
948              desc->pg_count > wsize))
949                 desc->pg_ioflags &= ~FLUSH_COND_STABLE;
950
951
952         offset = 0;
953         nbytes = desc->pg_count;
954         do {
955                 size_t len = min(nbytes, wsize);
956
957                 data = nfs_writedata_alloc(1);
958                 if (!data)
959                         goto out_bad;
960                 data->pagevec[0] = page;
961                 nfs_write_rpcsetup(req, data, len, offset, desc->pg_ioflags);
962                 list_add(&data->list, res);
963                 requests++;
964                 nbytes -= len;
965                 offset += len;
966         } while (nbytes != 0);
967         atomic_set(&req->wb_complete, requests);
968         desc->pg_rpc_callops = &nfs_write_partial_ops;
969         return ret;
970
971 out_bad:
972         while (!list_empty(res)) {
973                 data = list_entry(res->next, struct nfs_write_data, list);
974                 list_del(&data->list);
975                 nfs_writedata_free(data);
976         }
977         nfs_redirty_request(req);
978         return -ENOMEM;
979 }
980
981 /*
982  * Create an RPC task for the given write request and kick it.
983  * The page must have been locked by the caller.
984  *
985  * It may happen that the page we're passed is not marked dirty.
986  * This is the case if nfs_updatepage detects a conflicting request
987  * that has been written but not committed.
988  */
989 static int nfs_flush_one(struct nfs_pageio_descriptor *desc, struct list_head *res)
990 {
991         struct nfs_page         *req;
992         struct page             **pages;
993         struct nfs_write_data   *data;
994         struct list_head *head = &desc->pg_list;
995         int ret = 0;
996
997         data = nfs_writedata_alloc(nfs_page_array_len(desc->pg_base,
998                                                       desc->pg_count));
999         if (!data) {
1000                 while (!list_empty(head)) {
1001                         req = nfs_list_entry(head->next);
1002                         nfs_list_remove_request(req);
1003                         nfs_redirty_request(req);
1004                 }
1005                 ret = -ENOMEM;
1006                 goto out;
1007         }
1008         pages = data->pagevec;
1009         while (!list_empty(head)) {
1010                 req = nfs_list_entry(head->next);
1011                 nfs_list_remove_request(req);
1012                 nfs_list_add_request(req, &data->pages);
1013                 *pages++ = req->wb_page;
1014         }
1015         req = nfs_list_entry(data->pages.next);
1016
1017         if ((desc->pg_ioflags & FLUSH_COND_STABLE) &&
1018             (desc->pg_moreio || NFS_I(desc->pg_inode)->ncommit))
1019                 desc->pg_ioflags &= ~FLUSH_COND_STABLE;
1020
1021         /* Set up the argument struct */
1022         nfs_write_rpcsetup(req, data, desc->pg_count, 0, desc->pg_ioflags);
1023         list_add(&data->list, res);
1024         desc->pg_rpc_callops = &nfs_write_full_ops;
1025 out:
1026         return ret;
1027 }
1028
1029 int nfs_generic_flush(struct nfs_pageio_descriptor *desc, struct list_head *head)
1030 {
1031         if (desc->pg_bsize < PAGE_CACHE_SIZE)
1032                 return nfs_flush_multi(desc, head);
1033         return nfs_flush_one(desc, head);
1034 }
1035
1036 static int nfs_generic_pg_writepages(struct nfs_pageio_descriptor *desc)
1037 {
1038         LIST_HEAD(head);
1039         int ret;
1040
1041         ret = nfs_generic_flush(desc, &head);
1042         if (ret == 0)
1043                 ret = nfs_do_multiple_writes(&head, desc->pg_rpc_callops,
1044                                 desc->pg_ioflags);
1045         return ret;
1046 }
1047
1048 static const struct nfs_pageio_ops nfs_pageio_write_ops = {
1049         .pg_test = nfs_generic_pg_test,
1050         .pg_doio = nfs_generic_pg_writepages,
1051 };
1052
1053 void nfs_pageio_init_write_mds(struct nfs_pageio_descriptor *pgio,
1054                                   struct inode *inode, int ioflags)
1055 {
1056         nfs_pageio_init(pgio, inode, &nfs_pageio_write_ops,
1057                                 NFS_SERVER(inode)->wsize, ioflags);
1058 }
1059
1060 void nfs_pageio_reset_write_mds(struct nfs_pageio_descriptor *pgio)
1061 {
1062         pgio->pg_ops = &nfs_pageio_write_ops;
1063         pgio->pg_bsize = NFS_SERVER(pgio->pg_inode)->wsize;
1064 }
1065 EXPORT_SYMBOL_GPL(nfs_pageio_reset_write_mds);
1066
1067 static void nfs_pageio_init_write(struct nfs_pageio_descriptor *pgio,
1068                                   struct inode *inode, int ioflags)
1069 {
1070         if (!pnfs_pageio_init_write(pgio, inode, ioflags))
1071                 nfs_pageio_init_write_mds(pgio, inode, ioflags);
1072 }
1073
1074 /*
1075  * Handle a write reply that flushed part of a page.
1076  */
1077 static void nfs_writeback_done_partial(struct rpc_task *task, void *calldata)
1078 {
1079         struct nfs_write_data   *data = calldata;
1080
1081         dprintk("NFS: %5u write(%s/%lld %d@%lld)",
1082                 task->tk_pid,
1083                 data->req->wb_context->dentry->d_inode->i_sb->s_id,
1084                 (long long)
1085                   NFS_FILEID(data->req->wb_context->dentry->d_inode),
1086                 data->req->wb_bytes, (long long)req_offset(data->req));
1087
1088         nfs_writeback_done(task, data);
1089 }
1090
1091 static void nfs_writeback_release_partial(void *calldata)
1092 {
1093         struct nfs_write_data   *data = calldata;
1094         struct nfs_page         *req = data->req;
1095         struct page             *page = req->wb_page;
1096         int status = data->task.tk_status;
1097
1098         if (status < 0) {
1099                 nfs_set_pageerror(page);
1100                 nfs_context_set_write_error(req->wb_context, status);
1101                 dprintk(", error = %d\n", status);
1102                 goto out;
1103         }
1104
1105         if (nfs_write_need_commit(data)) {
1106                 struct inode *inode = page->mapping->host;
1107
1108                 spin_lock(&inode->i_lock);
1109                 if (test_bit(PG_NEED_RESCHED, &req->wb_flags)) {
1110                         /* Do nothing we need to resend the writes */
1111                 } else if (!test_and_set_bit(PG_NEED_COMMIT, &req->wb_flags)) {
1112                         memcpy(&req->wb_verf, &data->verf, sizeof(req->wb_verf));
1113                         dprintk(" defer commit\n");
1114                 } else if (memcmp(&req->wb_verf, &data->verf, sizeof(req->wb_verf))) {
1115                         set_bit(PG_NEED_RESCHED, &req->wb_flags);
1116                         clear_bit(PG_NEED_COMMIT, &req->wb_flags);
1117                         dprintk(" server reboot detected\n");
1118                 }
1119                 spin_unlock(&inode->i_lock);
1120         } else
1121                 dprintk(" OK\n");
1122
1123 out:
1124         if (atomic_dec_and_test(&req->wb_complete))
1125                 nfs_writepage_release(req, data);
1126         nfs_writedata_release(calldata);
1127 }
1128
1129 #if defined(CONFIG_NFS_V4_1)
1130 void nfs_write_prepare(struct rpc_task *task, void *calldata)
1131 {
1132         struct nfs_write_data *data = calldata;
1133
1134         if (nfs4_setup_sequence(NFS_SERVER(data->inode),
1135                                 &data->args.seq_args,
1136                                 &data->res.seq_res, task))
1137                 return;
1138         rpc_call_start(task);
1139 }
1140 #endif /* CONFIG_NFS_V4_1 */
1141
1142 static const struct rpc_call_ops nfs_write_partial_ops = {
1143 #if defined(CONFIG_NFS_V4_1)
1144         .rpc_call_prepare = nfs_write_prepare,
1145 #endif /* CONFIG_NFS_V4_1 */
1146         .rpc_call_done = nfs_writeback_done_partial,
1147         .rpc_release = nfs_writeback_release_partial,
1148 };
1149
1150 /*
1151  * Handle a write reply that flushes a whole page.
1152  *
1153  * FIXME: There is an inherent race with invalidate_inode_pages and
1154  *        writebacks since the page->count is kept > 1 for as long
1155  *        as the page has a write request pending.
1156  */
1157 static void nfs_writeback_done_full(struct rpc_task *task, void *calldata)
1158 {
1159         struct nfs_write_data   *data = calldata;
1160
1161         nfs_writeback_done(task, data);
1162 }
1163
1164 static void nfs_writeback_release_full(void *calldata)
1165 {
1166         struct nfs_write_data   *data = calldata;
1167         int status = data->task.tk_status;
1168
1169         /* Update attributes as result of writeback. */
1170         while (!list_empty(&data->pages)) {
1171                 struct nfs_page *req = nfs_list_entry(data->pages.next);
1172                 struct page *page = req->wb_page;
1173
1174                 nfs_list_remove_request(req);
1175
1176                 dprintk("NFS: %5u write (%s/%lld %d@%lld)",
1177                         data->task.tk_pid,
1178                         req->wb_context->dentry->d_inode->i_sb->s_id,
1179                         (long long)NFS_FILEID(req->wb_context->dentry->d_inode),
1180                         req->wb_bytes,
1181                         (long long)req_offset(req));
1182
1183                 if (status < 0) {
1184                         nfs_set_pageerror(page);
1185                         nfs_context_set_write_error(req->wb_context, status);
1186                         dprintk(", error = %d\n", status);
1187                         goto remove_request;
1188                 }
1189
1190                 if (nfs_write_need_commit(data)) {
1191                         memcpy(&req->wb_verf, &data->verf, sizeof(req->wb_verf));
1192                         nfs_mark_request_commit(req, data->lseg);
1193                         dprintk(" marked for commit\n");
1194                         goto next;
1195                 }
1196                 dprintk(" OK\n");
1197 remove_request:
1198                 nfs_inode_remove_request(req);
1199         next:
1200                 nfs_unlock_request(req);
1201                 nfs_end_page_writeback(page);
1202         }
1203         nfs_writedata_release(calldata);
1204 }
1205
1206 static const struct rpc_call_ops nfs_write_full_ops = {
1207 #if defined(CONFIG_NFS_V4_1)
1208         .rpc_call_prepare = nfs_write_prepare,
1209 #endif /* CONFIG_NFS_V4_1 */
1210         .rpc_call_done = nfs_writeback_done_full,
1211         .rpc_release = nfs_writeback_release_full,
1212 };
1213
1214
1215 /*
1216  * This function is called when the WRITE call is complete.
1217  */
1218 void nfs_writeback_done(struct rpc_task *task, struct nfs_write_data *data)
1219 {
1220         struct nfs_writeargs    *argp = &data->args;
1221         struct nfs_writeres     *resp = &data->res;
1222         int status;
1223
1224         dprintk("NFS: %5u nfs_writeback_done (status %d)\n",
1225                 task->tk_pid, task->tk_status);
1226
1227         /*
1228          * ->write_done will attempt to use post-op attributes to detect
1229          * conflicting writes by other clients.  A strict interpretation
1230          * of close-to-open would allow us to continue caching even if
1231          * another writer had changed the file, but some applications
1232          * depend on tighter cache coherency when writing.
1233          */
1234         status = NFS_PROTO(data->inode)->write_done(task, data);
1235         if (status != 0)
1236                 return;
1237         nfs_add_stats(data->inode, NFSIOS_SERVERWRITTENBYTES, resp->count);
1238
1239 #if defined(CONFIG_NFS_V3) || defined(CONFIG_NFS_V4)
1240         if (resp->verf->committed < argp->stable && task->tk_status >= 0) {
1241                 /* We tried a write call, but the server did not
1242                  * commit data to stable storage even though we
1243                  * requested it.
1244                  * Note: There is a known bug in Tru64 < 5.0 in which
1245                  *       the server reports NFS_DATA_SYNC, but performs
1246                  *       NFS_FILE_SYNC. We therefore implement this checking
1247                  *       as a dprintk() in order to avoid filling syslog.
1248                  */
1249                 static unsigned long    complain;
1250
1251                 /* Note this will print the MDS for a DS write */
1252                 if (time_before(complain, jiffies)) {
1253                         dprintk("NFS:       faulty NFS server %s:"
1254                                 " (committed = %d) != (stable = %d)\n",
1255                                 NFS_SERVER(data->inode)->nfs_client->cl_hostname,
1256                                 resp->verf->committed, argp->stable);
1257                         complain = jiffies + 300 * HZ;
1258                 }
1259         }
1260 #endif
1261         /* Is this a short write? */
1262         if (task->tk_status >= 0 && resp->count < argp->count) {
1263                 static unsigned long    complain;
1264
1265                 nfs_inc_stats(data->inode, NFSIOS_SHORTWRITE);
1266
1267                 /* Has the server at least made some progress? */
1268                 if (resp->count != 0) {
1269                         /* Was this an NFSv2 write or an NFSv3 stable write? */
1270                         if (resp->verf->committed != NFS_UNSTABLE) {
1271                                 /* Resend from where the server left off */
1272                                 data->mds_offset += resp->count;
1273                                 argp->offset += resp->count;
1274                                 argp->pgbase += resp->count;
1275                                 argp->count -= resp->count;
1276                         } else {
1277                                 /* Resend as a stable write in order to avoid
1278                                  * headaches in the case of a server crash.
1279                                  */
1280                                 argp->stable = NFS_FILE_SYNC;
1281                         }
1282                         rpc_restart_call_prepare(task);
1283                         return;
1284                 }
1285                 if (time_before(complain, jiffies)) {
1286                         printk(KERN_WARNING
1287                                "NFS: Server wrote zero bytes, expected %u.\n",
1288                                         argp->count);
1289                         complain = jiffies + 300 * HZ;
1290                 }
1291                 /* Can't do anything about it except throw an error. */
1292                 task->tk_status = -EIO;
1293         }
1294         return;
1295 }
1296
1297
1298 #if defined(CONFIG_NFS_V3) || defined(CONFIG_NFS_V4)
1299 static int nfs_commit_set_lock(struct nfs_inode *nfsi, int may_wait)
1300 {
1301         int ret;
1302
1303         if (!test_and_set_bit(NFS_INO_COMMIT, &nfsi->flags))
1304                 return 1;
1305         if (!may_wait)
1306                 return 0;
1307         ret = out_of_line_wait_on_bit_lock(&nfsi->flags,
1308                                 NFS_INO_COMMIT,
1309                                 nfs_wait_bit_killable,
1310                                 TASK_KILLABLE);
1311         return (ret < 0) ? ret : 1;
1312 }
1313
1314 void nfs_commit_clear_lock(struct nfs_inode *nfsi)
1315 {
1316         clear_bit(NFS_INO_COMMIT, &nfsi->flags);
1317         smp_mb__after_clear_bit();
1318         wake_up_bit(&nfsi->flags, NFS_INO_COMMIT);
1319 }
1320 EXPORT_SYMBOL_GPL(nfs_commit_clear_lock);
1321
1322 void nfs_commitdata_release(void *data)
1323 {
1324         struct nfs_write_data *wdata = data;
1325
1326         put_lseg(wdata->lseg);
1327         put_nfs_open_context(wdata->args.context);
1328         nfs_commit_free(wdata);
1329 }
1330 EXPORT_SYMBOL_GPL(nfs_commitdata_release);
1331
1332 int nfs_initiate_commit(struct nfs_write_data *data, struct rpc_clnt *clnt,
1333                         const struct rpc_call_ops *call_ops,
1334                         int how)
1335 {
1336         struct rpc_task *task;
1337         int priority = flush_task_priority(how);
1338         struct rpc_message msg = {
1339                 .rpc_argp = &data->args,
1340                 .rpc_resp = &data->res,
1341                 .rpc_cred = data->cred,
1342         };
1343         struct rpc_task_setup task_setup_data = {
1344                 .task = &data->task,
1345                 .rpc_client = clnt,
1346                 .rpc_message = &msg,
1347                 .callback_ops = call_ops,
1348                 .callback_data = data,
1349                 .workqueue = nfsiod_workqueue,
1350                 .flags = RPC_TASK_ASYNC,
1351                 .priority = priority,
1352         };
1353         /* Set up the initial task struct.  */
1354         NFS_PROTO(data->inode)->commit_setup(data, &msg);
1355
1356         dprintk("NFS: %5u initiated commit call\n", data->task.tk_pid);
1357
1358         task = rpc_run_task(&task_setup_data);
1359         if (IS_ERR(task))
1360                 return PTR_ERR(task);
1361         if (how & FLUSH_SYNC)
1362                 rpc_wait_for_completion_task(task);
1363         rpc_put_task(task);
1364         return 0;
1365 }
1366 EXPORT_SYMBOL_GPL(nfs_initiate_commit);
1367
1368 /*
1369  * Set up the argument/result storage required for the RPC call.
1370  */
1371 void nfs_init_commit(struct nfs_write_data *data,
1372                             struct list_head *head,
1373                             struct pnfs_layout_segment *lseg)
1374 {
1375         struct nfs_page *first = nfs_list_entry(head->next);
1376         struct inode *inode = first->wb_context->dentry->d_inode;
1377
1378         /* Set up the RPC argument and reply structs
1379          * NB: take care not to mess about with data->commit et al. */
1380
1381         list_splice_init(head, &data->pages);
1382
1383         data->inode       = inode;
1384         data->cred        = first->wb_context->cred;
1385         data->lseg        = lseg; /* reference transferred */
1386         data->mds_ops     = &nfs_commit_ops;
1387
1388         data->args.fh     = NFS_FH(data->inode);
1389         /* Note: we always request a commit of the entire inode */
1390         data->args.offset = 0;
1391         data->args.count  = 0;
1392         data->args.context = get_nfs_open_context(first->wb_context);
1393         data->res.count   = 0;
1394         data->res.fattr   = &data->fattr;
1395         data->res.verf    = &data->verf;
1396         nfs_fattr_init(&data->fattr);
1397 }
1398 EXPORT_SYMBOL_GPL(nfs_init_commit);
1399
1400 void nfs_retry_commit(struct list_head *page_list,
1401                       struct pnfs_layout_segment *lseg)
1402 {
1403         struct nfs_page *req;
1404
1405         while (!list_empty(page_list)) {
1406                 req = nfs_list_entry(page_list->next);
1407                 nfs_list_remove_request(req);
1408                 nfs_mark_request_commit(req, lseg);
1409                 dec_zone_page_state(req->wb_page, NR_UNSTABLE_NFS);
1410                 dec_bdi_stat(req->wb_page->mapping->backing_dev_info,
1411                              BDI_RECLAIMABLE);
1412                 nfs_unlock_request(req);
1413         }
1414 }
1415 EXPORT_SYMBOL_GPL(nfs_retry_commit);
1416
1417 /*
1418  * Commit dirty pages
1419  */
1420 static int
1421 nfs_commit_list(struct inode *inode, struct list_head *head, int how)
1422 {
1423         struct nfs_write_data   *data;
1424
1425         data = nfs_commitdata_alloc();
1426
1427         if (!data)
1428                 goto out_bad;
1429
1430         /* Set up the argument struct */
1431         nfs_init_commit(data, head, NULL);
1432         return nfs_initiate_commit(data, NFS_CLIENT(inode), data->mds_ops, how);
1433  out_bad:
1434         nfs_retry_commit(head, NULL);
1435         nfs_commit_clear_lock(NFS_I(inode));
1436         return -ENOMEM;
1437 }
1438
1439 /*
1440  * COMMIT call returned
1441  */
1442 static void nfs_commit_done(struct rpc_task *task, void *calldata)
1443 {
1444         struct nfs_write_data   *data = calldata;
1445
1446         dprintk("NFS: %5u nfs_commit_done (status %d)\n",
1447                                 task->tk_pid, task->tk_status);
1448
1449         /* Call the NFS version-specific code */
1450         NFS_PROTO(data->inode)->commit_done(task, data);
1451 }
1452
1453 void nfs_commit_release_pages(struct nfs_write_data *data)
1454 {
1455         struct nfs_page *req;
1456         int status = data->task.tk_status;
1457
1458         while (!list_empty(&data->pages)) {
1459                 req = nfs_list_entry(data->pages.next);
1460                 nfs_list_remove_request(req);
1461                 nfs_clear_request_commit(req);
1462
1463                 dprintk("NFS:       commit (%s/%lld %d@%lld)",
1464                         req->wb_context->dentry->d_sb->s_id,
1465                         (long long)NFS_FILEID(req->wb_context->dentry->d_inode),
1466                         req->wb_bytes,
1467                         (long long)req_offset(req));
1468                 if (status < 0) {
1469                         nfs_context_set_write_error(req->wb_context, status);
1470                         nfs_inode_remove_request(req);
1471                         dprintk(", error = %d\n", status);
1472                         goto next;
1473                 }
1474
1475                 /* Okay, COMMIT succeeded, apparently. Check the verifier
1476                  * returned by the server against all stored verfs. */
1477                 if (!memcmp(req->wb_verf.verifier, data->verf.verifier, sizeof(data->verf.verifier))) {
1478                         /* We have a match */
1479                         nfs_inode_remove_request(req);
1480                         dprintk(" OK\n");
1481                         goto next;
1482                 }
1483                 /* We have a mismatch. Write the page again */
1484                 dprintk(" mismatch\n");
1485                 nfs_mark_request_dirty(req);
1486         next:
1487                 nfs_unlock_request(req);
1488         }
1489 }
1490 EXPORT_SYMBOL_GPL(nfs_commit_release_pages);
1491
1492 static void nfs_commit_release(void *calldata)
1493 {
1494         struct nfs_write_data *data = calldata;
1495
1496         nfs_commit_release_pages(data);
1497         nfs_commit_clear_lock(NFS_I(data->inode));
1498         nfs_commitdata_release(calldata);
1499 }
1500
1501 static const struct rpc_call_ops nfs_commit_ops = {
1502 #if defined(CONFIG_NFS_V4_1)
1503         .rpc_call_prepare = nfs_write_prepare,
1504 #endif /* CONFIG_NFS_V4_1 */
1505         .rpc_call_done = nfs_commit_done,
1506         .rpc_release = nfs_commit_release,
1507 };
1508
1509 int nfs_commit_inode(struct inode *inode, int how)
1510 {
1511         LIST_HEAD(head);
1512         int may_wait = how & FLUSH_SYNC;
1513         int res;
1514
1515         res = nfs_commit_set_lock(NFS_I(inode), may_wait);
1516         if (res <= 0)
1517                 goto out_mark_dirty;
1518         res = nfs_scan_commit(inode, &head, 0, 0);
1519         if (res) {
1520                 int error;
1521
1522                 error = pnfs_commit_list(inode, &head, how);
1523                 if (error == PNFS_NOT_ATTEMPTED)
1524                         error = nfs_commit_list(inode, &head, how);
1525                 if (error < 0)
1526                         return error;
1527                 if (!may_wait)
1528                         goto out_mark_dirty;
1529                 error = wait_on_bit(&NFS_I(inode)->flags,
1530                                 NFS_INO_COMMIT,
1531                                 nfs_wait_bit_killable,
1532                                 TASK_KILLABLE);
1533                 if (error < 0)
1534                         return error;
1535         } else
1536                 nfs_commit_clear_lock(NFS_I(inode));
1537         return res;
1538         /* Note: If we exit without ensuring that the commit is complete,
1539          * we must mark the inode as dirty. Otherwise, future calls to
1540          * sync_inode() with the WB_SYNC_ALL flag set will fail to ensure
1541          * that the data is on the disk.
1542          */
1543 out_mark_dirty:
1544         __mark_inode_dirty(inode, I_DIRTY_DATASYNC);
1545         return res;
1546 }
1547
1548 static int nfs_commit_unstable_pages(struct inode *inode, struct writeback_control *wbc)
1549 {
1550         struct nfs_inode *nfsi = NFS_I(inode);
1551         int flags = FLUSH_SYNC;
1552         int ret = 0;
1553
1554         /* no commits means nothing needs to be done */
1555         if (!nfsi->ncommit)
1556                 return ret;
1557
1558         if (wbc->sync_mode == WB_SYNC_NONE) {
1559                 /* Don't commit yet if this is a non-blocking flush and there
1560                  * are a lot of outstanding writes for this mapping.
1561                  */
1562                 if (nfsi->ncommit <= (nfsi->npages >> 1))
1563                         goto out_mark_dirty;
1564
1565                 /* don't wait for the COMMIT response */
1566                 flags = 0;
1567         }
1568
1569         ret = nfs_commit_inode(inode, flags);
1570         if (ret >= 0) {
1571                 if (wbc->sync_mode == WB_SYNC_NONE) {
1572                         if (ret < wbc->nr_to_write)
1573                                 wbc->nr_to_write -= ret;
1574                         else
1575                                 wbc->nr_to_write = 0;
1576                 }
1577                 return 0;
1578         }
1579 out_mark_dirty:
1580         __mark_inode_dirty(inode, I_DIRTY_DATASYNC);
1581         return ret;
1582 }
1583 #else
1584 static int nfs_commit_unstable_pages(struct inode *inode, struct writeback_control *wbc)
1585 {
1586         return 0;
1587 }
1588 #endif
1589
1590 int nfs_write_inode(struct inode *inode, struct writeback_control *wbc)
1591 {
1592         int ret;
1593
1594         ret = nfs_commit_unstable_pages(inode, wbc);
1595         if (ret >= 0 && test_bit(NFS_INO_LAYOUTCOMMIT, &NFS_I(inode)->flags)) {
1596                 int status;
1597                 bool sync = true;
1598
1599                 if (wbc->sync_mode == WB_SYNC_NONE)
1600                         sync = false;
1601
1602                 status = pnfs_layoutcommit_inode(inode, sync);
1603                 if (status < 0)
1604                         return status;
1605         }
1606         return ret;
1607 }
1608
1609 /*
1610  * flush the inode to disk.
1611  */
1612 int nfs_wb_all(struct inode *inode)
1613 {
1614         struct writeback_control wbc = {
1615                 .sync_mode = WB_SYNC_ALL,
1616                 .nr_to_write = LONG_MAX,
1617                 .range_start = 0,
1618                 .range_end = LLONG_MAX,
1619         };
1620
1621         return sync_inode(inode, &wbc);
1622 }
1623
1624 int nfs_wb_page_cancel(struct inode *inode, struct page *page)
1625 {
1626         struct nfs_page *req;
1627         int ret = 0;
1628
1629         BUG_ON(!PageLocked(page));
1630         for (;;) {
1631                 wait_on_page_writeback(page);
1632                 req = nfs_page_find_request(page);
1633                 if (req == NULL)
1634                         break;
1635                 if (nfs_lock_request_dontget(req)) {
1636                         nfs_inode_remove_request(req);
1637                         /*
1638                          * In case nfs_inode_remove_request has marked the
1639                          * page as being dirty
1640                          */
1641                         cancel_dirty_page(page, PAGE_CACHE_SIZE);
1642                         nfs_unlock_request(req);
1643                         break;
1644                 }
1645                 ret = nfs_wait_on_request(req);
1646                 nfs_release_request(req);
1647                 if (ret < 0)
1648                         break;
1649         }
1650         return ret;
1651 }
1652
1653 /*
1654  * Write back all requests on one page - we do this before reading it.
1655  */
1656 int nfs_wb_page(struct inode *inode, struct page *page)
1657 {
1658         loff_t range_start = page_offset(page);
1659         loff_t range_end = range_start + (loff_t)(PAGE_CACHE_SIZE - 1);
1660         struct writeback_control wbc = {
1661                 .sync_mode = WB_SYNC_ALL,
1662                 .nr_to_write = 0,
1663                 .range_start = range_start,
1664                 .range_end = range_end,
1665         };
1666         int ret;
1667
1668         for (;;) {
1669                 wait_on_page_writeback(page);
1670                 if (clear_page_dirty_for_io(page)) {
1671                         ret = nfs_writepage_locked(page, &wbc);
1672                         if (ret < 0)
1673                                 goto out_error;
1674                         continue;
1675                 }
1676                 if (!PagePrivate(page))
1677                         break;
1678                 ret = nfs_commit_inode(inode, FLUSH_SYNC);
1679                 if (ret < 0)
1680                         goto out_error;
1681         }
1682         return 0;
1683 out_error:
1684         return ret;
1685 }
1686
1687 #ifdef CONFIG_MIGRATION
1688 int nfs_migrate_page(struct address_space *mapping, struct page *newpage,
1689                 struct page *page, enum migrate_mode mode)
1690 {
1691         /*
1692          * If PagePrivate is set, then the page is currently associated with
1693          * an in-progress read or write request. Don't try to migrate it.
1694          *
1695          * FIXME: we could do this in principle, but we'll need a way to ensure
1696          *        that we can safely release the inode reference while holding
1697          *        the page lock.
1698          */
1699         if (PagePrivate(page))
1700                 return -EBUSY;
1701
1702         nfs_fscache_release_page(page, GFP_KERNEL);
1703
1704         return migrate_page(mapping, newpage, page, mode);
1705 }
1706 #endif
1707
1708 int __init nfs_init_writepagecache(void)
1709 {
1710         nfs_wdata_cachep = kmem_cache_create("nfs_write_data",
1711                                              sizeof(struct nfs_write_data),
1712                                              0, SLAB_HWCACHE_ALIGN,
1713                                              NULL);
1714         if (nfs_wdata_cachep == NULL)
1715                 return -ENOMEM;
1716
1717         nfs_wdata_mempool = mempool_create_slab_pool(MIN_POOL_WRITE,
1718                                                      nfs_wdata_cachep);
1719         if (nfs_wdata_mempool == NULL)
1720                 return -ENOMEM;
1721
1722         nfs_commit_mempool = mempool_create_slab_pool(MIN_POOL_COMMIT,
1723                                                       nfs_wdata_cachep);
1724         if (nfs_commit_mempool == NULL)
1725                 return -ENOMEM;
1726
1727         /*
1728          * NFS congestion size, scale with available memory.
1729          *
1730          *  64MB:    8192k
1731          * 128MB:   11585k
1732          * 256MB:   16384k
1733          * 512MB:   23170k
1734          *   1GB:   32768k
1735          *   2GB:   46340k
1736          *   4GB:   65536k
1737          *   8GB:   92681k
1738          *  16GB:  131072k
1739          *
1740          * This allows larger machines to have larger/more transfers.
1741          * Limit the default to 256M
1742          */
1743         nfs_congestion_kb = (16*int_sqrt(totalram_pages)) << (PAGE_SHIFT-10);
1744         if (nfs_congestion_kb > 256*1024)
1745                 nfs_congestion_kb = 256*1024;
1746
1747         return 0;
1748 }
1749
1750 void nfs_destroy_writepagecache(void)
1751 {
1752         mempool_destroy(nfs_commit_mempool);
1753         mempool_destroy(nfs_wdata_mempool);
1754         kmem_cache_destroy(nfs_wdata_cachep);
1755 }
1756