GNU Linux-libre 4.9.283-gnu1
[releases.git] / fs / nfs / pnfs.c
1 /*
2  *  pNFS functions to call and manage layout drivers.
3  *
4  *  Copyright (c) 2002 [year of first publication]
5  *  The Regents of the University of Michigan
6  *  All Rights Reserved
7  *
8  *  Dean Hildebrand <dhildebz@umich.edu>
9  *
10  *  Permission is granted to use, copy, create derivative works, and
11  *  redistribute this software and such derivative works for any purpose,
12  *  so long as the name of the University of Michigan is not used in
13  *  any advertising or publicity pertaining to the use or distribution
14  *  of this software without specific, written prior authorization. If
15  *  the above copyright notice or any other identification of the
16  *  University of Michigan is included in any copy of any portion of
17  *  this software, then the disclaimer below must also be included.
18  *
19  *  This software is provided as is, without representation or warranty
20  *  of any kind either express or implied, including without limitation
21  *  the implied warranties of merchantability, fitness for a particular
22  *  purpose, or noninfringement.  The Regents of the University of
23  *  Michigan shall not be liable for any damages, including special,
24  *  indirect, incidental, or consequential damages, with respect to any
25  *  claim arising out of or in connection with the use of the software,
26  *  even if it has been or is hereafter advised of the possibility of
27  *  such damages.
28  */
29
30 #include <linux/nfs_fs.h>
31 #include <linux/nfs_page.h>
32 #include <linux/module.h>
33 #include <linux/sort.h>
34 #include "internal.h"
35 #include "pnfs.h"
36 #include "iostat.h"
37 #include "nfs4trace.h"
38 #include "delegation.h"
39 #include "nfs42.h"
40
41 #define NFSDBG_FACILITY         NFSDBG_PNFS
42 #define PNFS_LAYOUTGET_RETRY_TIMEOUT (120*HZ)
43
44 /* Locking:
45  *
46  * pnfs_spinlock:
47  *      protects pnfs_modules_tbl.
48  */
49 static DEFINE_SPINLOCK(pnfs_spinlock);
50
51 /*
52  * pnfs_modules_tbl holds all pnfs modules
53  */
54 static LIST_HEAD(pnfs_modules_tbl);
55
56 static void pnfs_layoutreturn_before_put_layout_hdr(struct pnfs_layout_hdr *lo);
57
58 /* Return the registered pnfs layout driver module matching given id */
59 static struct pnfs_layoutdriver_type *
60 find_pnfs_driver_locked(u32 id)
61 {
62         struct pnfs_layoutdriver_type *local;
63
64         list_for_each_entry(local, &pnfs_modules_tbl, pnfs_tblid)
65                 if (local->id == id)
66                         goto out;
67         local = NULL;
68 out:
69         dprintk("%s: Searching for id %u, found %p\n", __func__, id, local);
70         return local;
71 }
72
73 static struct pnfs_layoutdriver_type *
74 find_pnfs_driver(u32 id)
75 {
76         struct pnfs_layoutdriver_type *local;
77
78         spin_lock(&pnfs_spinlock);
79         local = find_pnfs_driver_locked(id);
80         if (local != NULL && !try_module_get(local->owner)) {
81                 dprintk("%s: Could not grab reference on module\n", __func__);
82                 local = NULL;
83         }
84         spin_unlock(&pnfs_spinlock);
85         return local;
86 }
87
88 void
89 unset_pnfs_layoutdriver(struct nfs_server *nfss)
90 {
91         if (nfss->pnfs_curr_ld) {
92                 if (nfss->pnfs_curr_ld->clear_layoutdriver)
93                         nfss->pnfs_curr_ld->clear_layoutdriver(nfss);
94                 /* Decrement the MDS count. Purge the deviceid cache if zero */
95                 if (atomic_dec_and_test(&nfss->nfs_client->cl_mds_count))
96                         nfs4_deviceid_purge_client(nfss->nfs_client);
97                 module_put(nfss->pnfs_curr_ld->owner);
98         }
99         nfss->pnfs_curr_ld = NULL;
100 }
101
102 /*
103  * When the server sends a list of layout types, we choose one in the order
104  * given in the list below.
105  *
106  * FIXME: should this list be configurable in some fashion? module param?
107  *        mount option? something else?
108  */
109 static const u32 ld_prefs[] = {
110         LAYOUT_SCSI,
111         LAYOUT_BLOCK_VOLUME,
112         LAYOUT_OSD2_OBJECTS,
113         LAYOUT_FLEX_FILES,
114         LAYOUT_NFSV4_1_FILES,
115         0
116 };
117
118 static int
119 ld_cmp(const void *e1, const void *e2)
120 {
121         u32 ld1 = *((u32 *)e1);
122         u32 ld2 = *((u32 *)e2);
123         int i;
124
125         for (i = 0; ld_prefs[i] != 0; i++) {
126                 if (ld1 == ld_prefs[i])
127                         return -1;
128
129                 if (ld2 == ld_prefs[i])
130                         return 1;
131         }
132         return 0;
133 }
134
135 /*
136  * Try to set the server's pnfs module to the pnfs layout type specified by id.
137  * Currently only one pNFS layout driver per filesystem is supported.
138  *
139  * @ids array of layout types supported by MDS.
140  */
141 void
142 set_pnfs_layoutdriver(struct nfs_server *server, const struct nfs_fh *mntfh,
143                       struct nfs_fsinfo *fsinfo)
144 {
145         struct pnfs_layoutdriver_type *ld_type = NULL;
146         u32 id;
147         int i;
148
149         if (fsinfo->nlayouttypes == 0)
150                 goto out_no_driver;
151         if (!(server->nfs_client->cl_exchange_flags &
152                  (EXCHGID4_FLAG_USE_NON_PNFS | EXCHGID4_FLAG_USE_PNFS_MDS))) {
153                 printk(KERN_ERR "NFS: %s: cl_exchange_flags 0x%x\n",
154                         __func__, server->nfs_client->cl_exchange_flags);
155                 goto out_no_driver;
156         }
157
158         sort(fsinfo->layouttype, fsinfo->nlayouttypes,
159                 sizeof(*fsinfo->layouttype), ld_cmp, NULL);
160
161         for (i = 0; i < fsinfo->nlayouttypes; i++) {
162                 id = fsinfo->layouttype[i];
163                 ld_type = find_pnfs_driver(id);
164                 if (!ld_type) {
165                         request_module("%s-%u", LAYOUT_NFSV4_1_MODULE_PREFIX,
166                                         id);
167                         ld_type = find_pnfs_driver(id);
168                 }
169                 if (ld_type)
170                         break;
171         }
172
173         if (!ld_type) {
174                 dprintk("%s: No pNFS module found!\n", __func__);
175                 goto out_no_driver;
176         }
177
178         server->pnfs_curr_ld = ld_type;
179         if (ld_type->set_layoutdriver
180             && ld_type->set_layoutdriver(server, mntfh)) {
181                 printk(KERN_ERR "NFS: %s: Error initializing pNFS layout "
182                         "driver %u.\n", __func__, id);
183                 module_put(ld_type->owner);
184                 goto out_no_driver;
185         }
186         /* Bump the MDS count */
187         atomic_inc(&server->nfs_client->cl_mds_count);
188
189         dprintk("%s: pNFS module for %u set\n", __func__, id);
190         return;
191
192 out_no_driver:
193         dprintk("%s: Using NFSv4 I/O\n", __func__);
194         server->pnfs_curr_ld = NULL;
195 }
196
197 int
198 pnfs_register_layoutdriver(struct pnfs_layoutdriver_type *ld_type)
199 {
200         int status = -EINVAL;
201         struct pnfs_layoutdriver_type *tmp;
202
203         if (ld_type->id == 0) {
204                 printk(KERN_ERR "NFS: %s id 0 is reserved\n", __func__);
205                 return status;
206         }
207         if (!ld_type->alloc_lseg || !ld_type->free_lseg) {
208                 printk(KERN_ERR "NFS: %s Layout driver must provide "
209                        "alloc_lseg and free_lseg.\n", __func__);
210                 return status;
211         }
212
213         spin_lock(&pnfs_spinlock);
214         tmp = find_pnfs_driver_locked(ld_type->id);
215         if (!tmp) {
216                 list_add(&ld_type->pnfs_tblid, &pnfs_modules_tbl);
217                 status = 0;
218                 dprintk("%s Registering id:%u name:%s\n", __func__, ld_type->id,
219                         ld_type->name);
220         } else {
221                 printk(KERN_ERR "NFS: %s Module with id %d already loaded!\n",
222                         __func__, ld_type->id);
223         }
224         spin_unlock(&pnfs_spinlock);
225
226         return status;
227 }
228 EXPORT_SYMBOL_GPL(pnfs_register_layoutdriver);
229
230 void
231 pnfs_unregister_layoutdriver(struct pnfs_layoutdriver_type *ld_type)
232 {
233         dprintk("%s Deregistering id:%u\n", __func__, ld_type->id);
234         spin_lock(&pnfs_spinlock);
235         list_del(&ld_type->pnfs_tblid);
236         spin_unlock(&pnfs_spinlock);
237 }
238 EXPORT_SYMBOL_GPL(pnfs_unregister_layoutdriver);
239
240 /*
241  * pNFS client layout cache
242  */
243
244 /* Need to hold i_lock if caller does not already hold reference */
245 void
246 pnfs_get_layout_hdr(struct pnfs_layout_hdr *lo)
247 {
248         atomic_inc(&lo->plh_refcount);
249 }
250
251 static struct pnfs_layout_hdr *
252 pnfs_alloc_layout_hdr(struct inode *ino, gfp_t gfp_flags)
253 {
254         struct pnfs_layoutdriver_type *ld = NFS_SERVER(ino)->pnfs_curr_ld;
255         return ld->alloc_layout_hdr(ino, gfp_flags);
256 }
257
258 static void
259 pnfs_free_layout_hdr(struct pnfs_layout_hdr *lo)
260 {
261         struct nfs_server *server = NFS_SERVER(lo->plh_inode);
262         struct pnfs_layoutdriver_type *ld = server->pnfs_curr_ld;
263
264         if (!list_empty(&lo->plh_layouts)) {
265                 struct nfs_client *clp = server->nfs_client;
266
267                 spin_lock(&clp->cl_lock);
268                 list_del_init(&lo->plh_layouts);
269                 spin_unlock(&clp->cl_lock);
270         }
271         put_rpccred(lo->plh_lc_cred);
272         return ld->free_layout_hdr(lo);
273 }
274
275 static void
276 pnfs_detach_layout_hdr(struct pnfs_layout_hdr *lo)
277 {
278         struct nfs_inode *nfsi = NFS_I(lo->plh_inode);
279         dprintk("%s: freeing layout cache %p\n", __func__, lo);
280         nfsi->layout = NULL;
281         /* Reset MDS Threshold I/O counters */
282         nfsi->write_io = 0;
283         nfsi->read_io = 0;
284 }
285
286 void
287 pnfs_put_layout_hdr(struct pnfs_layout_hdr *lo)
288 {
289         struct inode *inode = lo->plh_inode;
290
291         pnfs_layoutreturn_before_put_layout_hdr(lo);
292
293         if (atomic_dec_and_lock(&lo->plh_refcount, &inode->i_lock)) {
294                 if (!list_empty(&lo->plh_segs))
295                         WARN_ONCE(1, "NFS: BUG unfreed layout segments.\n");
296                 pnfs_detach_layout_hdr(lo);
297                 spin_unlock(&inode->i_lock);
298                 pnfs_free_layout_hdr(lo);
299         }
300 }
301
302 static void
303 pnfs_clear_layoutreturn_info(struct pnfs_layout_hdr *lo)
304 {
305         lo->plh_return_iomode = 0;
306         lo->plh_return_seq = 0;
307         clear_bit(NFS_LAYOUT_RETURN_REQUESTED, &lo->plh_flags);
308 }
309
310 /*
311  * Mark a pnfs_layout_hdr and all associated layout segments as invalid
312  *
313  * In order to continue using the pnfs_layout_hdr, a full recovery
314  * is required.
315  * Note that caller must hold inode->i_lock.
316  */
317 int
318 pnfs_mark_layout_stateid_invalid(struct pnfs_layout_hdr *lo,
319                 struct list_head *lseg_list)
320 {
321         struct pnfs_layout_range range = {
322                 .iomode = IOMODE_ANY,
323                 .offset = 0,
324                 .length = NFS4_MAX_UINT64,
325         };
326
327         set_bit(NFS_LAYOUT_INVALID_STID, &lo->plh_flags);
328         pnfs_clear_layoutreturn_info(lo);
329         return pnfs_mark_matching_lsegs_invalid(lo, lseg_list, &range, 0);
330 }
331
332 static int
333 pnfs_iomode_to_fail_bit(u32 iomode)
334 {
335         return iomode == IOMODE_RW ?
336                 NFS_LAYOUT_RW_FAILED : NFS_LAYOUT_RO_FAILED;
337 }
338
339 static void
340 pnfs_layout_set_fail_bit(struct pnfs_layout_hdr *lo, int fail_bit)
341 {
342         lo->plh_retry_timestamp = jiffies;
343         if (!test_and_set_bit(fail_bit, &lo->plh_flags))
344                 atomic_inc(&lo->plh_refcount);
345 }
346
347 static void
348 pnfs_layout_clear_fail_bit(struct pnfs_layout_hdr *lo, int fail_bit)
349 {
350         if (test_and_clear_bit(fail_bit, &lo->plh_flags))
351                 atomic_dec(&lo->plh_refcount);
352 }
353
354 static void
355 pnfs_layout_io_set_failed(struct pnfs_layout_hdr *lo, u32 iomode)
356 {
357         struct inode *inode = lo->plh_inode;
358         struct pnfs_layout_range range = {
359                 .iomode = iomode,
360                 .offset = 0,
361                 .length = NFS4_MAX_UINT64,
362         };
363         LIST_HEAD(head);
364
365         spin_lock(&inode->i_lock);
366         pnfs_layout_set_fail_bit(lo, pnfs_iomode_to_fail_bit(iomode));
367         pnfs_mark_matching_lsegs_invalid(lo, &head, &range, 0);
368         spin_unlock(&inode->i_lock);
369         pnfs_free_lseg_list(&head);
370         dprintk("%s Setting layout IOMODE_%s fail bit\n", __func__,
371                         iomode == IOMODE_RW ?  "RW" : "READ");
372 }
373
374 static bool
375 pnfs_layout_io_test_failed(struct pnfs_layout_hdr *lo, u32 iomode)
376 {
377         unsigned long start, end;
378         int fail_bit = pnfs_iomode_to_fail_bit(iomode);
379
380         if (test_bit(fail_bit, &lo->plh_flags) == 0)
381                 return false;
382         end = jiffies;
383         start = end - PNFS_LAYOUTGET_RETRY_TIMEOUT;
384         if (!time_in_range(lo->plh_retry_timestamp, start, end)) {
385                 /* It is time to retry the failed layoutgets */
386                 pnfs_layout_clear_fail_bit(lo, fail_bit);
387                 return false;
388         }
389         return true;
390 }
391
392 static void
393 pnfs_init_lseg(struct pnfs_layout_hdr *lo, struct pnfs_layout_segment *lseg,
394                 const struct pnfs_layout_range *range,
395                 const nfs4_stateid *stateid)
396 {
397         INIT_LIST_HEAD(&lseg->pls_list);
398         INIT_LIST_HEAD(&lseg->pls_lc_list);
399         atomic_set(&lseg->pls_refcount, 1);
400         set_bit(NFS_LSEG_VALID, &lseg->pls_flags);
401         lseg->pls_layout = lo;
402         lseg->pls_range = *range;
403         lseg->pls_seq = be32_to_cpu(stateid->seqid);
404 }
405
406 static void pnfs_free_lseg(struct pnfs_layout_segment *lseg)
407 {
408         struct inode *ino = lseg->pls_layout->plh_inode;
409
410         NFS_SERVER(ino)->pnfs_curr_ld->free_lseg(lseg);
411 }
412
413 static void
414 pnfs_layout_remove_lseg(struct pnfs_layout_hdr *lo,
415                 struct pnfs_layout_segment *lseg)
416 {
417         struct inode *inode = lo->plh_inode;
418
419         WARN_ON(test_bit(NFS_LSEG_VALID, &lseg->pls_flags));
420         list_del_init(&lseg->pls_list);
421         /* Matched by pnfs_get_layout_hdr in pnfs_layout_insert_lseg */
422         atomic_dec(&lo->plh_refcount);
423         if (list_empty(&lo->plh_segs) &&
424             !test_bit(NFS_LAYOUT_RETURN_REQUESTED, &lo->plh_flags) &&
425             !test_bit(NFS_LAYOUT_RETURN, &lo->plh_flags)) {
426                 if (atomic_read(&lo->plh_outstanding) == 0)
427                         set_bit(NFS_LAYOUT_INVALID_STID, &lo->plh_flags);
428                 clear_bit(NFS_LAYOUT_BULK_RECALL, &lo->plh_flags);
429         }
430         rpc_wake_up(&NFS_SERVER(inode)->roc_rpcwaitq);
431 }
432
433 void
434 pnfs_put_lseg(struct pnfs_layout_segment *lseg)
435 {
436         struct pnfs_layout_hdr *lo;
437         struct inode *inode;
438
439         if (!lseg)
440                 return;
441
442         dprintk("%s: lseg %p ref %d valid %d\n", __func__, lseg,
443                 atomic_read(&lseg->pls_refcount),
444                 test_bit(NFS_LSEG_VALID, &lseg->pls_flags));
445
446         lo = lseg->pls_layout;
447         inode = lo->plh_inode;
448
449         if (atomic_dec_and_lock(&lseg->pls_refcount, &inode->i_lock)) {
450                 if (test_bit(NFS_LSEG_VALID, &lseg->pls_flags)) {
451                         spin_unlock(&inode->i_lock);
452                         return;
453                 }
454                 pnfs_get_layout_hdr(lo);
455                 pnfs_layout_remove_lseg(lo, lseg);
456                 spin_unlock(&inode->i_lock);
457                 pnfs_free_lseg(lseg);
458                 pnfs_put_layout_hdr(lo);
459         }
460 }
461 EXPORT_SYMBOL_GPL(pnfs_put_lseg);
462
463 static void pnfs_free_lseg_async_work(struct work_struct *work)
464 {
465         struct pnfs_layout_segment *lseg;
466         struct pnfs_layout_hdr *lo;
467
468         lseg = container_of(work, struct pnfs_layout_segment, pls_work);
469         lo = lseg->pls_layout;
470
471         pnfs_free_lseg(lseg);
472         pnfs_put_layout_hdr(lo);
473 }
474
475 static void pnfs_free_lseg_async(struct pnfs_layout_segment *lseg)
476 {
477         INIT_WORK(&lseg->pls_work, pnfs_free_lseg_async_work);
478         schedule_work(&lseg->pls_work);
479 }
480
481 void
482 pnfs_put_lseg_locked(struct pnfs_layout_segment *lseg)
483 {
484         if (!lseg)
485                 return;
486
487         assert_spin_locked(&lseg->pls_layout->plh_inode->i_lock);
488
489         dprintk("%s: lseg %p ref %d valid %d\n", __func__, lseg,
490                 atomic_read(&lseg->pls_refcount),
491                 test_bit(NFS_LSEG_VALID, &lseg->pls_flags));
492         if (atomic_dec_and_test(&lseg->pls_refcount)) {
493                 struct pnfs_layout_hdr *lo = lseg->pls_layout;
494                 if (test_bit(NFS_LSEG_VALID, &lseg->pls_flags))
495                         return;
496                 pnfs_get_layout_hdr(lo);
497                 pnfs_layout_remove_lseg(lo, lseg);
498                 pnfs_free_lseg_async(lseg);
499         }
500 }
501 EXPORT_SYMBOL_GPL(pnfs_put_lseg_locked);
502
503 static u64
504 end_offset(u64 start, u64 len)
505 {
506         u64 end;
507
508         end = start + len;
509         return end >= start ? end : NFS4_MAX_UINT64;
510 }
511
512 /*
513  * is l2 fully contained in l1?
514  *   start1                             end1
515  *   [----------------------------------)
516  *           start2           end2
517  *           [----------------)
518  */
519 static bool
520 pnfs_lseg_range_contained(const struct pnfs_layout_range *l1,
521                  const struct pnfs_layout_range *l2)
522 {
523         u64 start1 = l1->offset;
524         u64 end1 = end_offset(start1, l1->length);
525         u64 start2 = l2->offset;
526         u64 end2 = end_offset(start2, l2->length);
527
528         return (start1 <= start2) && (end1 >= end2);
529 }
530
531 /*
532  * is l1 and l2 intersecting?
533  *   start1                             end1
534  *   [----------------------------------)
535  *                              start2           end2
536  *                              [----------------)
537  */
538 static bool
539 pnfs_lseg_range_intersecting(const struct pnfs_layout_range *l1,
540                     const struct pnfs_layout_range *l2)
541 {
542         u64 start1 = l1->offset;
543         u64 end1 = end_offset(start1, l1->length);
544         u64 start2 = l2->offset;
545         u64 end2 = end_offset(start2, l2->length);
546
547         return (end1 == NFS4_MAX_UINT64 || end1 > start2) &&
548                (end2 == NFS4_MAX_UINT64 || end2 > start1);
549 }
550
551 static bool pnfs_lseg_dec_and_remove_zero(struct pnfs_layout_segment *lseg,
552                 struct list_head *tmp_list)
553 {
554         if (!atomic_dec_and_test(&lseg->pls_refcount))
555                 return false;
556         pnfs_layout_remove_lseg(lseg->pls_layout, lseg);
557         list_add(&lseg->pls_list, tmp_list);
558         return true;
559 }
560
561 /* Returns 1 if lseg is removed from list, 0 otherwise */
562 static int mark_lseg_invalid(struct pnfs_layout_segment *lseg,
563                              struct list_head *tmp_list)
564 {
565         int rv = 0;
566
567         if (test_and_clear_bit(NFS_LSEG_VALID, &lseg->pls_flags)) {
568                 /* Remove the reference keeping the lseg in the
569                  * list.  It will now be removed when all
570                  * outstanding io is finished.
571                  */
572                 dprintk("%s: lseg %p ref %d\n", __func__, lseg,
573                         atomic_read(&lseg->pls_refcount));
574                 if (pnfs_lseg_dec_and_remove_zero(lseg, tmp_list))
575                         rv = 1;
576         }
577         return rv;
578 }
579
580 /*
581  * Compare 2 layout stateid sequence ids, to see which is newer,
582  * taking into account wraparound issues.
583  */
584 static bool pnfs_seqid_is_newer(u32 s1, u32 s2)
585 {
586         return (s32)(s1 - s2) > 0;
587 }
588
589 static bool
590 pnfs_should_free_range(const struct pnfs_layout_range *lseg_range,
591                  const struct pnfs_layout_range *recall_range)
592 {
593         return (recall_range->iomode == IOMODE_ANY ||
594                 lseg_range->iomode == recall_range->iomode) &&
595                pnfs_lseg_range_intersecting(lseg_range, recall_range);
596 }
597
598 static bool
599 pnfs_match_lseg_recall(const struct pnfs_layout_segment *lseg,
600                 const struct pnfs_layout_range *recall_range,
601                 u32 seq)
602 {
603         if (seq != 0 && pnfs_seqid_is_newer(lseg->pls_seq, seq))
604                 return false;
605         if (recall_range == NULL)
606                 return true;
607         return pnfs_should_free_range(&lseg->pls_range, recall_range);
608 }
609
610 /**
611  * pnfs_mark_matching_lsegs_invalid - tear down lsegs or mark them for later
612  * @lo: layout header containing the lsegs
613  * @tmp_list: list head where doomed lsegs should go
614  * @recall_range: optional recall range argument to match (may be NULL)
615  * @seq: only invalidate lsegs obtained prior to this sequence (may be 0)
616  *
617  * Walk the list of lsegs in the layout header, and tear down any that should
618  * be destroyed. If "recall_range" is specified then the segment must match
619  * that range. If "seq" is non-zero, then only match segments that were handed
620  * out at or before that sequence.
621  *
622  * Returns number of matching invalid lsegs remaining in list after scanning
623  * it and purging them.
624  */
625 int
626 pnfs_mark_matching_lsegs_invalid(struct pnfs_layout_hdr *lo,
627                             struct list_head *tmp_list,
628                             const struct pnfs_layout_range *recall_range,
629                             u32 seq)
630 {
631         struct pnfs_layout_segment *lseg, *next;
632         int remaining = 0;
633
634         dprintk("%s:Begin lo %p\n", __func__, lo);
635
636         if (list_empty(&lo->plh_segs))
637                 return 0;
638         list_for_each_entry_safe(lseg, next, &lo->plh_segs, pls_list)
639                 if (pnfs_match_lseg_recall(lseg, recall_range, seq)) {
640                         dprintk("%s: freeing lseg %p iomode %d seq %u"
641                                 "offset %llu length %llu\n", __func__,
642                                 lseg, lseg->pls_range.iomode, lseg->pls_seq,
643                                 lseg->pls_range.offset, lseg->pls_range.length);
644                         if (!mark_lseg_invalid(lseg, tmp_list))
645                                 remaining++;
646                 }
647         dprintk("%s:Return %i\n", __func__, remaining);
648         return remaining;
649 }
650
651 /* note free_me must contain lsegs from a single layout_hdr */
652 void
653 pnfs_free_lseg_list(struct list_head *free_me)
654 {
655         struct pnfs_layout_segment *lseg, *tmp;
656
657         if (list_empty(free_me))
658                 return;
659
660         list_for_each_entry_safe(lseg, tmp, free_me, pls_list) {
661                 list_del(&lseg->pls_list);
662                 pnfs_free_lseg(lseg);
663         }
664 }
665
666 void
667 pnfs_destroy_layout(struct nfs_inode *nfsi)
668 {
669         struct pnfs_layout_hdr *lo;
670         LIST_HEAD(tmp_list);
671
672         spin_lock(&nfsi->vfs_inode.i_lock);
673         lo = nfsi->layout;
674         if (lo) {
675                 pnfs_get_layout_hdr(lo);
676                 pnfs_mark_layout_stateid_invalid(lo, &tmp_list);
677                 pnfs_layout_clear_fail_bit(lo, NFS_LAYOUT_RO_FAILED);
678                 pnfs_layout_clear_fail_bit(lo, NFS_LAYOUT_RW_FAILED);
679                 spin_unlock(&nfsi->vfs_inode.i_lock);
680                 pnfs_free_lseg_list(&tmp_list);
681                 pnfs_put_layout_hdr(lo);
682         } else
683                 spin_unlock(&nfsi->vfs_inode.i_lock);
684 }
685 EXPORT_SYMBOL_GPL(pnfs_destroy_layout);
686
687 static bool
688 pnfs_layout_add_bulk_destroy_list(struct inode *inode,
689                 struct list_head *layout_list)
690 {
691         struct pnfs_layout_hdr *lo;
692         bool ret = false;
693
694         spin_lock(&inode->i_lock);
695         lo = NFS_I(inode)->layout;
696         if (lo != NULL && list_empty(&lo->plh_bulk_destroy)) {
697                 pnfs_get_layout_hdr(lo);
698                 list_add(&lo->plh_bulk_destroy, layout_list);
699                 ret = true;
700         }
701         spin_unlock(&inode->i_lock);
702         return ret;
703 }
704
705 /* Caller must hold rcu_read_lock and clp->cl_lock */
706 static int
707 pnfs_layout_bulk_destroy_byserver_locked(struct nfs_client *clp,
708                 struct nfs_server *server,
709                 struct list_head *layout_list)
710 {
711         struct pnfs_layout_hdr *lo, *next;
712         struct inode *inode;
713
714         list_for_each_entry_safe(lo, next, &server->layouts, plh_layouts) {
715                 inode = igrab(lo->plh_inode);
716                 if (inode == NULL)
717                         continue;
718                 list_del_init(&lo->plh_layouts);
719                 if (pnfs_layout_add_bulk_destroy_list(inode, layout_list))
720                         continue;
721                 rcu_read_unlock();
722                 spin_unlock(&clp->cl_lock);
723                 iput(inode);
724                 spin_lock(&clp->cl_lock);
725                 rcu_read_lock();
726                 return -EAGAIN;
727         }
728         return 0;
729 }
730
731 static int
732 pnfs_layout_free_bulk_destroy_list(struct list_head *layout_list,
733                 bool is_bulk_recall)
734 {
735         struct pnfs_layout_hdr *lo;
736         struct inode *inode;
737         LIST_HEAD(lseg_list);
738         int ret = 0;
739
740         while (!list_empty(layout_list)) {
741                 lo = list_entry(layout_list->next, struct pnfs_layout_hdr,
742                                 plh_bulk_destroy);
743                 dprintk("%s freeing layout for inode %lu\n", __func__,
744                         lo->plh_inode->i_ino);
745                 inode = lo->plh_inode;
746
747                 pnfs_layoutcommit_inode(inode, false);
748
749                 spin_lock(&inode->i_lock);
750                 list_del_init(&lo->plh_bulk_destroy);
751                 if (pnfs_mark_layout_stateid_invalid(lo, &lseg_list)) {
752                         if (is_bulk_recall)
753                                 set_bit(NFS_LAYOUT_BULK_RECALL, &lo->plh_flags);
754                         ret = -EAGAIN;
755                 }
756                 spin_unlock(&inode->i_lock);
757                 pnfs_free_lseg_list(&lseg_list);
758                 /* Free all lsegs that are attached to commit buckets */
759                 nfs_commit_inode(inode, 0);
760                 pnfs_put_layout_hdr(lo);
761                 iput(inode);
762         }
763         return ret;
764 }
765
766 int
767 pnfs_destroy_layouts_byfsid(struct nfs_client *clp,
768                 struct nfs_fsid *fsid,
769                 bool is_recall)
770 {
771         struct nfs_server *server;
772         LIST_HEAD(layout_list);
773
774         spin_lock(&clp->cl_lock);
775         rcu_read_lock();
776 restart:
777         list_for_each_entry_rcu(server, &clp->cl_superblocks, client_link) {
778                 if (memcmp(&server->fsid, fsid, sizeof(*fsid)) != 0)
779                         continue;
780                 if (pnfs_layout_bulk_destroy_byserver_locked(clp,
781                                 server,
782                                 &layout_list) != 0)
783                         goto restart;
784         }
785         rcu_read_unlock();
786         spin_unlock(&clp->cl_lock);
787
788         if (list_empty(&layout_list))
789                 return 0;
790         return pnfs_layout_free_bulk_destroy_list(&layout_list, is_recall);
791 }
792
793 int
794 pnfs_destroy_layouts_byclid(struct nfs_client *clp,
795                 bool is_recall)
796 {
797         struct nfs_server *server;
798         LIST_HEAD(layout_list);
799
800         spin_lock(&clp->cl_lock);
801         rcu_read_lock();
802 restart:
803         list_for_each_entry_rcu(server, &clp->cl_superblocks, client_link) {
804                 if (pnfs_layout_bulk_destroy_byserver_locked(clp,
805                                         server,
806                                         &layout_list) != 0)
807                         goto restart;
808         }
809         rcu_read_unlock();
810         spin_unlock(&clp->cl_lock);
811
812         if (list_empty(&layout_list))
813                 return 0;
814         return pnfs_layout_free_bulk_destroy_list(&layout_list, is_recall);
815 }
816
817 /*
818  * Called by the state manger to remove all layouts established under an
819  * expired lease.
820  */
821 void
822 pnfs_destroy_all_layouts(struct nfs_client *clp)
823 {
824         nfs4_deviceid_mark_client_invalid(clp);
825         nfs4_deviceid_purge_client(clp);
826
827         pnfs_destroy_layouts_byclid(clp, false);
828 }
829
830 /* update lo->plh_stateid with new if is more recent */
831 void
832 pnfs_set_layout_stateid(struct pnfs_layout_hdr *lo, const nfs4_stateid *new,
833                         bool update_barrier)
834 {
835         u32 oldseq, newseq, new_barrier = 0;
836
837         oldseq = be32_to_cpu(lo->plh_stateid.seqid);
838         newseq = be32_to_cpu(new->seqid);
839
840         if (!pnfs_layout_is_valid(lo)) {
841                 nfs4_stateid_copy(&lo->plh_stateid, new);
842                 lo->plh_barrier = newseq;
843                 pnfs_clear_layoutreturn_info(lo);
844                 clear_bit(NFS_LAYOUT_INVALID_STID, &lo->plh_flags);
845                 return;
846         }
847         if (pnfs_seqid_is_newer(newseq, oldseq)) {
848                 nfs4_stateid_copy(&lo->plh_stateid, new);
849                 /*
850                  * Because of wraparound, we want to keep the barrier
851                  * "close" to the current seqids.
852                  */
853                 new_barrier = newseq - atomic_read(&lo->plh_outstanding);
854         }
855         if (update_barrier)
856                 new_barrier = be32_to_cpu(new->seqid);
857         else if (new_barrier == 0)
858                 return;
859         if (pnfs_seqid_is_newer(new_barrier, lo->plh_barrier))
860                 lo->plh_barrier = new_barrier;
861 }
862
863 static bool
864 pnfs_layout_stateid_blocked(const struct pnfs_layout_hdr *lo,
865                 const nfs4_stateid *stateid)
866 {
867         u32 seqid = be32_to_cpu(stateid->seqid);
868
869         return !pnfs_seqid_is_newer(seqid, lo->plh_barrier);
870 }
871
872 /* lget is set to 1 if called from inside send_layoutget call chain */
873 static bool
874 pnfs_layoutgets_blocked(const struct pnfs_layout_hdr *lo)
875 {
876         return lo->plh_block_lgets ||
877                 test_bit(NFS_LAYOUT_BULK_RECALL, &lo->plh_flags);
878 }
879
880 /*
881  * Get layout from server.
882  *    for now, assume that whole file layouts are requested.
883  *    arg->offset: 0
884  *    arg->length: all ones
885  */
886 static struct pnfs_layout_segment *
887 send_layoutget(struct pnfs_layout_hdr *lo,
888            struct nfs_open_context *ctx,
889            nfs4_stateid *stateid,
890            const struct pnfs_layout_range *range,
891            long *timeout, gfp_t gfp_flags)
892 {
893         struct inode *ino = lo->plh_inode;
894         struct nfs_server *server = NFS_SERVER(ino);
895         struct nfs4_layoutget *lgp;
896         loff_t i_size;
897
898         dprintk("--> %s\n", __func__);
899
900         /*
901          * Synchronously retrieve layout information from server and
902          * store in lseg. If we race with a concurrent seqid morphing
903          * op, then re-send the LAYOUTGET.
904          */
905         lgp = kzalloc(sizeof(*lgp), gfp_flags);
906         if (lgp == NULL)
907                 return ERR_PTR(-ENOMEM);
908
909         i_size = i_size_read(ino);
910
911         lgp->args.minlength = PAGE_SIZE;
912         if (lgp->args.minlength > range->length)
913                 lgp->args.minlength = range->length;
914         if (range->iomode == IOMODE_READ) {
915                 if (range->offset >= i_size)
916                         lgp->args.minlength = 0;
917                 else if (i_size - range->offset < lgp->args.minlength)
918                         lgp->args.minlength = i_size - range->offset;
919         }
920         lgp->args.maxcount = PNFS_LAYOUT_MAXSIZE;
921         pnfs_copy_range(&lgp->args.range, range);
922         lgp->args.type = server->pnfs_curr_ld->id;
923         lgp->args.inode = ino;
924         lgp->args.ctx = get_nfs_open_context(ctx);
925         nfs4_stateid_copy(&lgp->args.stateid, stateid);
926         lgp->gfp_flags = gfp_flags;
927         lgp->cred = lo->plh_lc_cred;
928
929         return nfs4_proc_layoutget(lgp, timeout, gfp_flags);
930 }
931
932 static void pnfs_clear_layoutcommit(struct inode *inode,
933                 struct list_head *head)
934 {
935         struct nfs_inode *nfsi = NFS_I(inode);
936         struct pnfs_layout_segment *lseg, *tmp;
937
938         if (!test_and_clear_bit(NFS_INO_LAYOUTCOMMIT, &nfsi->flags))
939                 return;
940         list_for_each_entry_safe(lseg, tmp, &nfsi->layout->plh_segs, pls_list) {
941                 if (!test_and_clear_bit(NFS_LSEG_LAYOUTCOMMIT, &lseg->pls_flags))
942                         continue;
943                 pnfs_lseg_dec_and_remove_zero(lseg, head);
944         }
945 }
946
947 void pnfs_clear_layoutreturn_waitbit(struct pnfs_layout_hdr *lo)
948 {
949         clear_bit_unlock(NFS_LAYOUT_RETURN, &lo->plh_flags);
950         clear_bit(NFS_LAYOUT_RETURN_LOCK, &lo->plh_flags);
951         smp_mb__after_atomic();
952         wake_up_bit(&lo->plh_flags, NFS_LAYOUT_RETURN);
953         rpc_wake_up(&NFS_SERVER(lo->plh_inode)->roc_rpcwaitq);
954 }
955
956 static bool
957 pnfs_prepare_layoutreturn(struct pnfs_layout_hdr *lo,
958                 nfs4_stateid *stateid,
959                 enum pnfs_iomode *iomode)
960 {
961         /* Serialise LAYOUTGET/LAYOUTRETURN */
962         if (atomic_read(&lo->plh_outstanding) != 0)
963                 return false;
964         if (test_and_set_bit(NFS_LAYOUT_RETURN_LOCK, &lo->plh_flags))
965                 return false;
966         set_bit(NFS_LAYOUT_RETURN, &lo->plh_flags);
967         pnfs_get_layout_hdr(lo);
968         if (test_bit(NFS_LAYOUT_RETURN_REQUESTED, &lo->plh_flags)) {
969                 if (stateid != NULL) {
970                         nfs4_stateid_copy(stateid, &lo->plh_stateid);
971                         if (lo->plh_return_seq != 0)
972                                 stateid->seqid = cpu_to_be32(lo->plh_return_seq);
973                 }
974                 if (iomode != NULL)
975                         *iomode = lo->plh_return_iomode;
976                 pnfs_clear_layoutreturn_info(lo);
977                 return true;
978         }
979         if (stateid != NULL)
980                 nfs4_stateid_copy(stateid, &lo->plh_stateid);
981         if (iomode != NULL)
982                 *iomode = IOMODE_ANY;
983         return true;
984 }
985
986 static int
987 pnfs_send_layoutreturn(struct pnfs_layout_hdr *lo, const nfs4_stateid *stateid,
988                        enum pnfs_iomode iomode, bool sync)
989 {
990         struct inode *ino = lo->plh_inode;
991         struct nfs4_layoutreturn *lrp;
992         int status = 0;
993
994         lrp = kzalloc(sizeof(*lrp), GFP_NOFS);
995         if (unlikely(lrp == NULL)) {
996                 status = -ENOMEM;
997                 spin_lock(&ino->i_lock);
998                 pnfs_clear_layoutreturn_waitbit(lo);
999                 spin_unlock(&ino->i_lock);
1000                 pnfs_put_layout_hdr(lo);
1001                 goto out;
1002         }
1003
1004         nfs4_stateid_copy(&lrp->args.stateid, stateid);
1005         lrp->args.layout_type = NFS_SERVER(ino)->pnfs_curr_ld->id;
1006         lrp->args.inode = ino;
1007         lrp->args.range.iomode = iomode;
1008         lrp->args.range.offset = 0;
1009         lrp->args.range.length = NFS4_MAX_UINT64;
1010         lrp->args.layout = lo;
1011         lrp->clp = NFS_SERVER(ino)->nfs_client;
1012         lrp->cred = lo->plh_lc_cred;
1013
1014         status = nfs4_proc_layoutreturn(lrp, sync);
1015 out:
1016         dprintk("<-- %s status: %d\n", __func__, status);
1017         return status;
1018 }
1019
1020 /* Return true if layoutreturn is needed */
1021 static bool
1022 pnfs_layout_need_return(struct pnfs_layout_hdr *lo)
1023 {
1024         struct pnfs_layout_segment *s;
1025
1026         if (!test_bit(NFS_LAYOUT_RETURN_REQUESTED, &lo->plh_flags))
1027                 return false;
1028
1029         /* Defer layoutreturn until all lsegs are done */
1030         list_for_each_entry(s, &lo->plh_segs, pls_list) {
1031                 if (test_bit(NFS_LSEG_LAYOUTRETURN, &s->pls_flags))
1032                         return false;
1033         }
1034
1035         return true;
1036 }
1037
1038 static void pnfs_layoutreturn_before_put_layout_hdr(struct pnfs_layout_hdr *lo)
1039 {
1040         struct inode *inode= lo->plh_inode;
1041
1042         if (!test_bit(NFS_LAYOUT_RETURN_REQUESTED, &lo->plh_flags))
1043                 return;
1044         spin_lock(&inode->i_lock);
1045         if (pnfs_layout_need_return(lo)) {
1046                 nfs4_stateid stateid;
1047                 enum pnfs_iomode iomode;
1048                 bool send;
1049
1050                 send = pnfs_prepare_layoutreturn(lo, &stateid, &iomode);
1051                 spin_unlock(&inode->i_lock);
1052                 if (send) {
1053                         /* Send an async layoutreturn so we dont deadlock */
1054                         pnfs_send_layoutreturn(lo, &stateid, iomode, false);
1055                 }
1056         } else
1057                 spin_unlock(&inode->i_lock);
1058 }
1059
1060 /*
1061  * Initiates a LAYOUTRETURN(FILE), and removes the pnfs_layout_hdr
1062  * when the layout segment list is empty.
1063  *
1064  * Note that a pnfs_layout_hdr can exist with an empty layout segment
1065  * list when LAYOUTGET has failed, or when LAYOUTGET succeeded, but the
1066  * deviceid is marked invalid.
1067  */
1068 int
1069 _pnfs_return_layout(struct inode *ino)
1070 {
1071         struct pnfs_layout_hdr *lo = NULL;
1072         struct nfs_inode *nfsi = NFS_I(ino);
1073         struct pnfs_layout_range range = {
1074                 .iomode         = IOMODE_ANY,
1075                 .offset         = 0,
1076                 .length         = NFS4_MAX_UINT64,
1077         };
1078         LIST_HEAD(tmp_list);
1079         nfs4_stateid stateid;
1080         int status = 0, empty;
1081         bool send;
1082
1083         dprintk("NFS: %s for inode %lu\n", __func__, ino->i_ino);
1084
1085         spin_lock(&ino->i_lock);
1086         lo = nfsi->layout;
1087         if (!lo) {
1088                 spin_unlock(&ino->i_lock);
1089                 dprintk("NFS: %s no layout to return\n", __func__);
1090                 goto out;
1091         }
1092         /* Reference matched in nfs4_layoutreturn_release */
1093         pnfs_get_layout_hdr(lo);
1094         empty = list_empty(&lo->plh_segs);
1095         pnfs_clear_layoutcommit(ino, &tmp_list);
1096         pnfs_mark_matching_lsegs_return(lo, &tmp_list, &range, 0);
1097
1098         if (NFS_SERVER(ino)->pnfs_curr_ld->return_range)
1099                 NFS_SERVER(ino)->pnfs_curr_ld->return_range(lo, &range);
1100
1101         /* Don't send a LAYOUTRETURN if list was initially empty */
1102         if (empty) {
1103                 spin_unlock(&ino->i_lock);
1104                 dprintk("NFS: %s no layout segments to return\n", __func__);
1105                 goto out_put_layout_hdr;
1106         }
1107
1108         send = pnfs_prepare_layoutreturn(lo, &stateid, NULL);
1109         spin_unlock(&ino->i_lock);
1110         pnfs_free_lseg_list(&tmp_list);
1111         if (send)
1112                 status = pnfs_send_layoutreturn(lo, &stateid, IOMODE_ANY, true);
1113 out_put_layout_hdr:
1114         pnfs_put_layout_hdr(lo);
1115 out:
1116         dprintk("<-- %s status: %d\n", __func__, status);
1117         return status;
1118 }
1119 EXPORT_SYMBOL_GPL(_pnfs_return_layout);
1120
1121 int
1122 pnfs_commit_and_return_layout(struct inode *inode)
1123 {
1124         struct pnfs_layout_hdr *lo;
1125         int ret;
1126
1127         spin_lock(&inode->i_lock);
1128         lo = NFS_I(inode)->layout;
1129         if (lo == NULL) {
1130                 spin_unlock(&inode->i_lock);
1131                 return 0;
1132         }
1133         pnfs_get_layout_hdr(lo);
1134         /* Block new layoutgets and read/write to ds */
1135         lo->plh_block_lgets++;
1136         spin_unlock(&inode->i_lock);
1137         filemap_fdatawait(inode->i_mapping);
1138         ret = pnfs_layoutcommit_inode(inode, true);
1139         if (ret == 0)
1140                 ret = _pnfs_return_layout(inode);
1141         spin_lock(&inode->i_lock);
1142         lo->plh_block_lgets--;
1143         spin_unlock(&inode->i_lock);
1144         pnfs_put_layout_hdr(lo);
1145         return ret;
1146 }
1147
1148 bool pnfs_roc(struct inode *ino)
1149 {
1150         struct nfs_inode *nfsi = NFS_I(ino);
1151         struct nfs_open_context *ctx;
1152         struct nfs4_state *state;
1153         struct pnfs_layout_hdr *lo;
1154         struct pnfs_layout_segment *lseg, *tmp;
1155         nfs4_stateid stateid;
1156         LIST_HEAD(tmp_list);
1157         bool found = false, layoutreturn = false, roc = false;
1158
1159         spin_lock(&ino->i_lock);
1160         lo = nfsi->layout;
1161         if (!lo || test_bit(NFS_LAYOUT_BULK_RECALL, &lo->plh_flags))
1162                 goto out_noroc;
1163
1164         /* no roc if we hold a delegation */
1165         if (nfs4_check_delegation(ino, FMODE_READ))
1166                 goto out_noroc;
1167
1168         list_for_each_entry(ctx, &nfsi->open_files, list) {
1169                 state = ctx->state;
1170                 /* Don't return layout if there is open file state */
1171                 if (state != NULL && state->state != 0)
1172                         goto out_noroc;
1173         }
1174
1175         /* always send layoutreturn if being marked so */
1176         if (test_bit(NFS_LAYOUT_RETURN_REQUESTED, &lo->plh_flags))
1177                 layoutreturn = pnfs_prepare_layoutreturn(lo,
1178                                 &stateid, NULL);
1179
1180         list_for_each_entry_safe(lseg, tmp, &lo->plh_segs, pls_list)
1181                 /* If we are sending layoutreturn, invalidate all valid lsegs */
1182                 if (layoutreturn || test_bit(NFS_LSEG_ROC, &lseg->pls_flags)) {
1183                         mark_lseg_invalid(lseg, &tmp_list);
1184                         found = true;
1185                 }
1186         /* ROC in two conditions:
1187          * 1. there are ROC lsegs
1188          * 2. we don't send layoutreturn
1189          */
1190         if (found && !layoutreturn) {
1191                 /* lo ref dropped in pnfs_roc_release() */
1192                 pnfs_get_layout_hdr(lo);
1193                 roc = true;
1194         }
1195
1196 out_noroc:
1197         spin_unlock(&ino->i_lock);
1198         pnfs_free_lseg_list(&tmp_list);
1199         pnfs_layoutcommit_inode(ino, true);
1200         if (layoutreturn)
1201                 pnfs_send_layoutreturn(lo, &stateid, IOMODE_ANY, true);
1202         return roc;
1203 }
1204
1205 void pnfs_roc_release(struct inode *ino)
1206 {
1207         struct pnfs_layout_hdr *lo;
1208
1209         spin_lock(&ino->i_lock);
1210         lo = NFS_I(ino)->layout;
1211         pnfs_clear_layoutreturn_waitbit(lo);
1212         if (atomic_dec_and_test(&lo->plh_refcount)) {
1213                 pnfs_detach_layout_hdr(lo);
1214                 spin_unlock(&ino->i_lock);
1215                 pnfs_free_layout_hdr(lo);
1216         } else
1217                 spin_unlock(&ino->i_lock);
1218 }
1219
1220 void pnfs_roc_set_barrier(struct inode *ino, u32 barrier)
1221 {
1222         struct pnfs_layout_hdr *lo;
1223
1224         spin_lock(&ino->i_lock);
1225         lo = NFS_I(ino)->layout;
1226         if (pnfs_seqid_is_newer(barrier, lo->plh_barrier))
1227                 lo->plh_barrier = barrier;
1228         spin_unlock(&ino->i_lock);
1229         trace_nfs4_layoutreturn_on_close(ino, 0);
1230 }
1231
1232 void pnfs_roc_get_barrier(struct inode *ino, u32 *barrier)
1233 {
1234         struct nfs_inode *nfsi = NFS_I(ino);
1235         struct pnfs_layout_hdr *lo;
1236         u32 current_seqid;
1237
1238         spin_lock(&ino->i_lock);
1239         lo = nfsi->layout;
1240         current_seqid = be32_to_cpu(lo->plh_stateid.seqid);
1241
1242         /* Since close does not return a layout stateid for use as
1243          * a barrier, we choose the worst-case barrier.
1244          */
1245         *barrier = current_seqid + atomic_read(&lo->plh_outstanding);
1246         spin_unlock(&ino->i_lock);
1247 }
1248
1249 bool pnfs_wait_on_layoutreturn(struct inode *ino, struct rpc_task *task)
1250 {
1251         struct nfs_inode *nfsi = NFS_I(ino);
1252         struct pnfs_layout_hdr *lo;
1253         bool sleep = false;
1254
1255         /* we might not have grabbed lo reference. so need to check under
1256          * i_lock */
1257         spin_lock(&ino->i_lock);
1258         lo = nfsi->layout;
1259         if (lo && test_bit(NFS_LAYOUT_RETURN, &lo->plh_flags)) {
1260                 rpc_sleep_on(&NFS_SERVER(ino)->roc_rpcwaitq, task, NULL);
1261                 sleep = true;
1262         }
1263         spin_unlock(&ino->i_lock);
1264         return sleep;
1265 }
1266
1267 /*
1268  * Compare two layout segments for sorting into layout cache.
1269  * We want to preferentially return RW over RO layouts, so ensure those
1270  * are seen first.
1271  */
1272 static s64
1273 pnfs_lseg_range_cmp(const struct pnfs_layout_range *l1,
1274            const struct pnfs_layout_range *l2)
1275 {
1276         s64 d;
1277
1278         /* high offset > low offset */
1279         d = l1->offset - l2->offset;
1280         if (d)
1281                 return d;
1282
1283         /* short length > long length */
1284         d = l2->length - l1->length;
1285         if (d)
1286                 return d;
1287
1288         /* read > read/write */
1289         return (int)(l1->iomode == IOMODE_READ) - (int)(l2->iomode == IOMODE_READ);
1290 }
1291
1292 static bool
1293 pnfs_lseg_range_is_after(const struct pnfs_layout_range *l1,
1294                 const struct pnfs_layout_range *l2)
1295 {
1296         return pnfs_lseg_range_cmp(l1, l2) > 0;
1297 }
1298
1299 static bool
1300 pnfs_lseg_no_merge(struct pnfs_layout_segment *lseg,
1301                 struct pnfs_layout_segment *old)
1302 {
1303         return false;
1304 }
1305
1306 void
1307 pnfs_generic_layout_insert_lseg(struct pnfs_layout_hdr *lo,
1308                    struct pnfs_layout_segment *lseg,
1309                    bool (*is_after)(const struct pnfs_layout_range *,
1310                            const struct pnfs_layout_range *),
1311                    bool (*do_merge)(struct pnfs_layout_segment *,
1312                            struct pnfs_layout_segment *),
1313                    struct list_head *free_me)
1314 {
1315         struct pnfs_layout_segment *lp, *tmp;
1316
1317         dprintk("%s:Begin\n", __func__);
1318
1319         list_for_each_entry_safe(lp, tmp, &lo->plh_segs, pls_list) {
1320                 if (test_bit(NFS_LSEG_VALID, &lp->pls_flags) == 0)
1321                         continue;
1322                 if (do_merge(lseg, lp)) {
1323                         mark_lseg_invalid(lp, free_me);
1324                         continue;
1325                 }
1326                 if (is_after(&lseg->pls_range, &lp->pls_range))
1327                         continue;
1328                 list_add_tail(&lseg->pls_list, &lp->pls_list);
1329                 dprintk("%s: inserted lseg %p "
1330                         "iomode %d offset %llu length %llu before "
1331                         "lp %p iomode %d offset %llu length %llu\n",
1332                         __func__, lseg, lseg->pls_range.iomode,
1333                         lseg->pls_range.offset, lseg->pls_range.length,
1334                         lp, lp->pls_range.iomode, lp->pls_range.offset,
1335                         lp->pls_range.length);
1336                 goto out;
1337         }
1338         list_add_tail(&lseg->pls_list, &lo->plh_segs);
1339         dprintk("%s: inserted lseg %p "
1340                 "iomode %d offset %llu length %llu at tail\n",
1341                 __func__, lseg, lseg->pls_range.iomode,
1342                 lseg->pls_range.offset, lseg->pls_range.length);
1343 out:
1344         pnfs_get_layout_hdr(lo);
1345
1346         dprintk("%s:Return\n", __func__);
1347 }
1348 EXPORT_SYMBOL_GPL(pnfs_generic_layout_insert_lseg);
1349
1350 static void
1351 pnfs_layout_insert_lseg(struct pnfs_layout_hdr *lo,
1352                    struct pnfs_layout_segment *lseg,
1353                    struct list_head *free_me)
1354 {
1355         struct inode *inode = lo->plh_inode;
1356         struct pnfs_layoutdriver_type *ld = NFS_SERVER(inode)->pnfs_curr_ld;
1357
1358         if (ld->add_lseg != NULL)
1359                 ld->add_lseg(lo, lseg, free_me);
1360         else
1361                 pnfs_generic_layout_insert_lseg(lo, lseg,
1362                                 pnfs_lseg_range_is_after,
1363                                 pnfs_lseg_no_merge,
1364                                 free_me);
1365 }
1366
1367 static struct pnfs_layout_hdr *
1368 alloc_init_layout_hdr(struct inode *ino,
1369                       struct nfs_open_context *ctx,
1370                       gfp_t gfp_flags)
1371 {
1372         struct pnfs_layout_hdr *lo;
1373
1374         lo = pnfs_alloc_layout_hdr(ino, gfp_flags);
1375         if (!lo)
1376                 return NULL;
1377         atomic_set(&lo->plh_refcount, 1);
1378         INIT_LIST_HEAD(&lo->plh_layouts);
1379         INIT_LIST_HEAD(&lo->plh_segs);
1380         INIT_LIST_HEAD(&lo->plh_bulk_destroy);
1381         lo->plh_inode = ino;
1382         lo->plh_lc_cred = get_rpccred(ctx->cred);
1383         lo->plh_flags |= 1 << NFS_LAYOUT_INVALID_STID;
1384         return lo;
1385 }
1386
1387 static struct pnfs_layout_hdr *
1388 pnfs_find_alloc_layout(struct inode *ino,
1389                        struct nfs_open_context *ctx,
1390                        gfp_t gfp_flags)
1391         __releases(&ino->i_lock)
1392         __acquires(&ino->i_lock)
1393 {
1394         struct nfs_inode *nfsi = NFS_I(ino);
1395         struct pnfs_layout_hdr *new = NULL;
1396
1397         dprintk("%s Begin ino=%p layout=%p\n", __func__, ino, nfsi->layout);
1398
1399         if (nfsi->layout != NULL)
1400                 goto out_existing;
1401         spin_unlock(&ino->i_lock);
1402         new = alloc_init_layout_hdr(ino, ctx, gfp_flags);
1403         spin_lock(&ino->i_lock);
1404
1405         if (likely(nfsi->layout == NULL)) {     /* Won the race? */
1406                 nfsi->layout = new;
1407                 return new;
1408         } else if (new != NULL)
1409                 pnfs_free_layout_hdr(new);
1410 out_existing:
1411         pnfs_get_layout_hdr(nfsi->layout);
1412         return nfsi->layout;
1413 }
1414
1415 /*
1416  * iomode matching rules:
1417  * iomode       lseg    strict match
1418  *                      iomode
1419  * -----        -----   ------ -----
1420  * ANY          READ    N/A    true
1421  * ANY          RW      N/A    true
1422  * RW           READ    N/A    false
1423  * RW           RW      N/A    true
1424  * READ         READ    N/A    true
1425  * READ         RW      true   false
1426  * READ         RW      false  true
1427  */
1428 static bool
1429 pnfs_lseg_range_match(const struct pnfs_layout_range *ls_range,
1430                  const struct pnfs_layout_range *range,
1431                  bool strict_iomode)
1432 {
1433         struct pnfs_layout_range range1;
1434
1435         if ((range->iomode == IOMODE_RW &&
1436              ls_range->iomode != IOMODE_RW) ||
1437             (range->iomode != ls_range->iomode &&
1438              strict_iomode) ||
1439             !pnfs_lseg_range_intersecting(ls_range, range))
1440                 return 0;
1441
1442         /* range1 covers only the first byte in the range */
1443         range1 = *range;
1444         range1.length = 1;
1445         return pnfs_lseg_range_contained(ls_range, &range1);
1446 }
1447
1448 /*
1449  * lookup range in layout
1450  */
1451 static struct pnfs_layout_segment *
1452 pnfs_find_lseg(struct pnfs_layout_hdr *lo,
1453                 struct pnfs_layout_range *range,
1454                 bool strict_iomode)
1455 {
1456         struct pnfs_layout_segment *lseg, *ret = NULL;
1457
1458         dprintk("%s:Begin\n", __func__);
1459
1460         list_for_each_entry(lseg, &lo->plh_segs, pls_list) {
1461                 if (test_bit(NFS_LSEG_VALID, &lseg->pls_flags) &&
1462                     !test_bit(NFS_LSEG_LAYOUTRETURN, &lseg->pls_flags) &&
1463                     pnfs_lseg_range_match(&lseg->pls_range, range,
1464                                           strict_iomode)) {
1465                         ret = pnfs_get_lseg(lseg);
1466                         break;
1467                 }
1468         }
1469
1470         dprintk("%s:Return lseg %p ref %d\n",
1471                 __func__, ret, ret ? atomic_read(&ret->pls_refcount) : 0);
1472         return ret;
1473 }
1474
1475 /*
1476  * Use mdsthreshold hints set at each OPEN to determine if I/O should go
1477  * to the MDS or over pNFS
1478  *
1479  * The nfs_inode read_io and write_io fields are cumulative counters reset
1480  * when there are no layout segments. Note that in pnfs_update_layout iomode
1481  * is set to IOMODE_READ for a READ request, and set to IOMODE_RW for a
1482  * WRITE request.
1483  *
1484  * A return of true means use MDS I/O.
1485  *
1486  * From rfc 5661:
1487  * If a file's size is smaller than the file size threshold, data accesses
1488  * SHOULD be sent to the metadata server.  If an I/O request has a length that
1489  * is below the I/O size threshold, the I/O SHOULD be sent to the metadata
1490  * server.  If both file size and I/O size are provided, the client SHOULD
1491  * reach or exceed  both thresholds before sending its read or write
1492  * requests to the data server.
1493  */
1494 static bool pnfs_within_mdsthreshold(struct nfs_open_context *ctx,
1495                                      struct inode *ino, int iomode)
1496 {
1497         struct nfs4_threshold *t = ctx->mdsthreshold;
1498         struct nfs_inode *nfsi = NFS_I(ino);
1499         loff_t fsize = i_size_read(ino);
1500         bool size = false, size_set = false, io = false, io_set = false, ret = false;
1501
1502         if (t == NULL)
1503                 return ret;
1504
1505         dprintk("%s bm=0x%x rd_sz=%llu wr_sz=%llu rd_io=%llu wr_io=%llu\n",
1506                 __func__, t->bm, t->rd_sz, t->wr_sz, t->rd_io_sz, t->wr_io_sz);
1507
1508         switch (iomode) {
1509         case IOMODE_READ:
1510                 if (t->bm & THRESHOLD_RD) {
1511                         dprintk("%s fsize %llu\n", __func__, fsize);
1512                         size_set = true;
1513                         if (fsize < t->rd_sz)
1514                                 size = true;
1515                 }
1516                 if (t->bm & THRESHOLD_RD_IO) {
1517                         dprintk("%s nfsi->read_io %llu\n", __func__,
1518                                 nfsi->read_io);
1519                         io_set = true;
1520                         if (nfsi->read_io < t->rd_io_sz)
1521                                 io = true;
1522                 }
1523                 break;
1524         case IOMODE_RW:
1525                 if (t->bm & THRESHOLD_WR) {
1526                         dprintk("%s fsize %llu\n", __func__, fsize);
1527                         size_set = true;
1528                         if (fsize < t->wr_sz)
1529                                 size = true;
1530                 }
1531                 if (t->bm & THRESHOLD_WR_IO) {
1532                         dprintk("%s nfsi->write_io %llu\n", __func__,
1533                                 nfsi->write_io);
1534                         io_set = true;
1535                         if (nfsi->write_io < t->wr_io_sz)
1536                                 io = true;
1537                 }
1538                 break;
1539         }
1540         if (size_set && io_set) {
1541                 if (size && io)
1542                         ret = true;
1543         } else if (size || io)
1544                 ret = true;
1545
1546         dprintk("<-- %s size %d io %d ret %d\n", __func__, size, io, ret);
1547         return ret;
1548 }
1549
1550 static bool pnfs_prepare_to_retry_layoutget(struct pnfs_layout_hdr *lo)
1551 {
1552         /*
1553          * send layoutcommit as it can hold up layoutreturn due to lseg
1554          * reference
1555          */
1556         pnfs_layoutcommit_inode(lo->plh_inode, false);
1557         return !wait_on_bit_action(&lo->plh_flags, NFS_LAYOUT_RETURN,
1558                                    nfs_wait_bit_killable,
1559                                    TASK_UNINTERRUPTIBLE);
1560 }
1561
1562 static void pnfs_clear_first_layoutget(struct pnfs_layout_hdr *lo)
1563 {
1564         unsigned long *bitlock = &lo->plh_flags;
1565
1566         clear_bit_unlock(NFS_LAYOUT_FIRST_LAYOUTGET, bitlock);
1567         smp_mb__after_atomic();
1568         wake_up_bit(bitlock, NFS_LAYOUT_FIRST_LAYOUTGET);
1569 }
1570
1571 /*
1572  * Layout segment is retreived from the server if not cached.
1573  * The appropriate layout segment is referenced and returned to the caller.
1574  */
1575 struct pnfs_layout_segment *
1576 pnfs_update_layout(struct inode *ino,
1577                    struct nfs_open_context *ctx,
1578                    loff_t pos,
1579                    u64 count,
1580                    enum pnfs_iomode iomode,
1581                    bool strict_iomode,
1582                    gfp_t gfp_flags)
1583 {
1584         struct pnfs_layout_range arg = {
1585                 .iomode = iomode,
1586                 .offset = pos,
1587                 .length = count,
1588         };
1589         unsigned pg_offset, seq;
1590         struct nfs_server *server = NFS_SERVER(ino);
1591         struct nfs_client *clp = server->nfs_client;
1592         struct pnfs_layout_hdr *lo = NULL;
1593         struct pnfs_layout_segment *lseg = NULL;
1594         nfs4_stateid stateid;
1595         long timeout = 0;
1596         unsigned long giveup = jiffies + (clp->cl_lease_time << 1);
1597         bool first;
1598
1599         if (!pnfs_enabled_sb(NFS_SERVER(ino))) {
1600                 trace_pnfs_update_layout(ino, pos, count, iomode, lo, lseg,
1601                                  PNFS_UPDATE_LAYOUT_NO_PNFS);
1602                 goto out;
1603         }
1604
1605         if (iomode == IOMODE_READ && i_size_read(ino) == 0) {
1606                 trace_pnfs_update_layout(ino, pos, count, iomode, lo, lseg,
1607                                  PNFS_UPDATE_LAYOUT_RD_ZEROLEN);
1608                 goto out;
1609         }
1610
1611         if (pnfs_within_mdsthreshold(ctx, ino, iomode)) {
1612                 trace_pnfs_update_layout(ino, pos, count, iomode, lo, lseg,
1613                                  PNFS_UPDATE_LAYOUT_MDSTHRESH);
1614                 goto out;
1615         }
1616
1617 lookup_again:
1618         nfs4_client_recover_expired_lease(clp);
1619         first = false;
1620         spin_lock(&ino->i_lock);
1621         lo = pnfs_find_alloc_layout(ino, ctx, gfp_flags);
1622         if (lo == NULL) {
1623                 spin_unlock(&ino->i_lock);
1624                 trace_pnfs_update_layout(ino, pos, count, iomode, lo, lseg,
1625                                  PNFS_UPDATE_LAYOUT_NOMEM);
1626                 goto out;
1627         }
1628
1629         /* Do we even need to bother with this? */
1630         if (test_bit(NFS_LAYOUT_BULK_RECALL, &lo->plh_flags)) {
1631                 trace_pnfs_update_layout(ino, pos, count, iomode, lo, lseg,
1632                                  PNFS_UPDATE_LAYOUT_BULK_RECALL);
1633                 dprintk("%s matches recall, use MDS\n", __func__);
1634                 goto out_unlock;
1635         }
1636
1637         /* if LAYOUTGET already failed once we don't try again */
1638         if (pnfs_layout_io_test_failed(lo, iomode)) {
1639                 trace_pnfs_update_layout(ino, pos, count, iomode, lo, lseg,
1640                                  PNFS_UPDATE_LAYOUT_IO_TEST_FAIL);
1641                 goto out_unlock;
1642         }
1643
1644         lseg = pnfs_find_lseg(lo, &arg, strict_iomode);
1645         if (lseg) {
1646                 trace_pnfs_update_layout(ino, pos, count, iomode, lo, lseg,
1647                                 PNFS_UPDATE_LAYOUT_FOUND_CACHED);
1648                 goto out_unlock;
1649         }
1650
1651         if (!nfs4_valid_open_stateid(ctx->state)) {
1652                 trace_pnfs_update_layout(ino, pos, count, iomode, lo, lseg,
1653                                 PNFS_UPDATE_LAYOUT_INVALID_OPEN);
1654                 goto out_unlock;
1655         }
1656
1657         /*
1658          * Choose a stateid for the LAYOUTGET. If we don't have a layout
1659          * stateid, or it has been invalidated, then we must use the open
1660          * stateid.
1661          */
1662         if (test_bit(NFS_LAYOUT_INVALID_STID, &lo->plh_flags)) {
1663
1664                 /*
1665                  * The first layoutget for the file. Need to serialize per
1666                  * RFC 5661 Errata 3208.
1667                  */
1668                 if (test_and_set_bit(NFS_LAYOUT_FIRST_LAYOUTGET,
1669                                      &lo->plh_flags)) {
1670                         spin_unlock(&ino->i_lock);
1671                         wait_on_bit(&lo->plh_flags, NFS_LAYOUT_FIRST_LAYOUTGET,
1672                                     TASK_UNINTERRUPTIBLE);
1673                         pnfs_put_layout_hdr(lo);
1674                         dprintk("%s retrying\n", __func__);
1675                         goto lookup_again;
1676                 }
1677
1678                 first = true;
1679                 do {
1680                         seq = read_seqbegin(&ctx->state->seqlock);
1681                         nfs4_stateid_copy(&stateid, &ctx->state->stateid);
1682                 } while (read_seqretry(&ctx->state->seqlock, seq));
1683         } else {
1684                 nfs4_stateid_copy(&stateid, &lo->plh_stateid);
1685         }
1686
1687         /*
1688          * Because we free lsegs before sending LAYOUTRETURN, we need to wait
1689          * for LAYOUTRETURN even if first is true.
1690          */
1691         if (test_bit(NFS_LAYOUT_RETURN, &lo->plh_flags)) {
1692                 spin_unlock(&ino->i_lock);
1693                 dprintk("%s wait for layoutreturn\n", __func__);
1694                 if (pnfs_prepare_to_retry_layoutget(lo)) {
1695                         if (first)
1696                                 pnfs_clear_first_layoutget(lo);
1697                         pnfs_put_layout_hdr(lo);
1698                         dprintk("%s retrying\n", __func__);
1699                         trace_pnfs_update_layout(ino, pos, count, iomode, lo,
1700                                         lseg, PNFS_UPDATE_LAYOUT_RETRY);
1701                         goto lookup_again;
1702                 }
1703                 trace_pnfs_update_layout(ino, pos, count, iomode, lo, lseg,
1704                                 PNFS_UPDATE_LAYOUT_RETURN);
1705                 goto out_put_layout_hdr;
1706         }
1707
1708         if (pnfs_layoutgets_blocked(lo)) {
1709                 trace_pnfs_update_layout(ino, pos, count, iomode, lo, lseg,
1710                                 PNFS_UPDATE_LAYOUT_BLOCKED);
1711                 goto out_unlock;
1712         }
1713         atomic_inc(&lo->plh_outstanding);
1714         spin_unlock(&ino->i_lock);
1715
1716         if (list_empty(&lo->plh_layouts)) {
1717                 /* The lo must be on the clp list if there is any
1718                  * chance of a CB_LAYOUTRECALL(FILE) coming in.
1719                  */
1720                 spin_lock(&clp->cl_lock);
1721                 if (list_empty(&lo->plh_layouts))
1722                         list_add_tail(&lo->plh_layouts, &server->layouts);
1723                 spin_unlock(&clp->cl_lock);
1724         }
1725
1726         pg_offset = arg.offset & ~PAGE_MASK;
1727         if (pg_offset) {
1728                 arg.offset -= pg_offset;
1729                 arg.length += pg_offset;
1730         }
1731         if (arg.length != NFS4_MAX_UINT64)
1732                 arg.length = PAGE_ALIGN(arg.length);
1733
1734         lseg = send_layoutget(lo, ctx, &stateid, &arg, &timeout, gfp_flags);
1735         trace_pnfs_update_layout(ino, pos, count, iomode, lo, lseg,
1736                                  PNFS_UPDATE_LAYOUT_SEND_LAYOUTGET);
1737         atomic_dec(&lo->plh_outstanding);
1738         if (IS_ERR(lseg)) {
1739                 switch(PTR_ERR(lseg)) {
1740                 case -EBUSY:
1741                         if (time_after(jiffies, giveup))
1742                                 lseg = NULL;
1743                         break;
1744                 case -ERECALLCONFLICT:
1745                         /* Huh? We hold no layouts, how is there a recall? */
1746                         if (first) {
1747                                 lseg = NULL;
1748                                 break;
1749                         }
1750                         /* Destroy the existing layout and start over */
1751                         if (time_after(jiffies, giveup))
1752                                 pnfs_destroy_layout(NFS_I(ino));
1753                         /* Fallthrough */
1754                 case -EAGAIN:
1755                         break;
1756                 default:
1757                         if (!nfs_error_is_fatal(PTR_ERR(lseg))) {
1758                                 pnfs_layout_clear_fail_bit(lo, pnfs_iomode_to_fail_bit(iomode));
1759                                 lseg = NULL;
1760                         }
1761                         goto out_put_layout_hdr;
1762                 }
1763                 if (lseg) {
1764                         if (first)
1765                                 pnfs_clear_first_layoutget(lo);
1766                         trace_pnfs_update_layout(ino, pos, count,
1767                                 iomode, lo, lseg, PNFS_UPDATE_LAYOUT_RETRY);
1768                         pnfs_put_layout_hdr(lo);
1769                         goto lookup_again;
1770                 }
1771         } else {
1772                 pnfs_layout_clear_fail_bit(lo, pnfs_iomode_to_fail_bit(iomode));
1773         }
1774
1775 out_put_layout_hdr:
1776         if (first)
1777                 pnfs_clear_first_layoutget(lo);
1778         pnfs_put_layout_hdr(lo);
1779 out:
1780         dprintk("%s: inode %s/%llu pNFS layout segment %s for "
1781                         "(%s, offset: %llu, length: %llu)\n",
1782                         __func__, ino->i_sb->s_id,
1783                         (unsigned long long)NFS_FILEID(ino),
1784                         IS_ERR_OR_NULL(lseg) ? "not found" : "found",
1785                         iomode==IOMODE_RW ?  "read/write" : "read-only",
1786                         (unsigned long long)pos,
1787                         (unsigned long long)count);
1788         return lseg;
1789 out_unlock:
1790         spin_unlock(&ino->i_lock);
1791         goto out_put_layout_hdr;
1792 }
1793 EXPORT_SYMBOL_GPL(pnfs_update_layout);
1794
1795 static bool
1796 pnfs_sanity_check_layout_range(struct pnfs_layout_range *range)
1797 {
1798         switch (range->iomode) {
1799         case IOMODE_READ:
1800         case IOMODE_RW:
1801                 break;
1802         default:
1803                 return false;
1804         }
1805         if (range->offset == NFS4_MAX_UINT64)
1806                 return false;
1807         if (range->length == 0)
1808                 return false;
1809         if (range->length != NFS4_MAX_UINT64 &&
1810             range->length > NFS4_MAX_UINT64 - range->offset)
1811                 return false;
1812         return true;
1813 }
1814
1815 struct pnfs_layout_segment *
1816 pnfs_layout_process(struct nfs4_layoutget *lgp)
1817 {
1818         struct pnfs_layout_hdr *lo = NFS_I(lgp->args.inode)->layout;
1819         struct nfs4_layoutget_res *res = &lgp->res;
1820         struct pnfs_layout_segment *lseg;
1821         struct inode *ino = lo->plh_inode;
1822         LIST_HEAD(free_me);
1823
1824         if (!pnfs_sanity_check_layout_range(&res->range))
1825                 return ERR_PTR(-EINVAL);
1826
1827         /* Inject layout blob into I/O device driver */
1828         lseg = NFS_SERVER(ino)->pnfs_curr_ld->alloc_lseg(lo, res, lgp->gfp_flags);
1829         if (IS_ERR_OR_NULL(lseg)) {
1830                 if (!lseg)
1831                         lseg = ERR_PTR(-ENOMEM);
1832
1833                 dprintk("%s: Could not allocate layout: error %ld\n",
1834                        __func__, PTR_ERR(lseg));
1835                 return lseg;
1836         }
1837
1838         pnfs_init_lseg(lo, lseg, &res->range, &res->stateid);
1839
1840         spin_lock(&ino->i_lock);
1841         if (pnfs_layoutgets_blocked(lo)) {
1842                 dprintk("%s forget reply due to state\n", __func__);
1843                 goto out_forget;
1844         }
1845
1846         if (nfs4_stateid_match_other(&lo->plh_stateid, &res->stateid)) {
1847                 /* existing state ID, make sure the sequence number matches. */
1848                 if (pnfs_layout_stateid_blocked(lo, &res->stateid)) {
1849                         dprintk("%s forget reply due to sequence\n", __func__);
1850                         goto out_forget;
1851                 }
1852                 pnfs_set_layout_stateid(lo, &res->stateid, false);
1853         } else {
1854                 /*
1855                  * We got an entirely new state ID.  Mark all segments for the
1856                  * inode invalid, and don't bother validating the stateid
1857                  * sequence number.
1858                  */
1859                 pnfs_mark_layout_stateid_invalid(lo, &free_me);
1860
1861                 pnfs_set_layout_stateid(lo, &res->stateid, true);
1862         }
1863
1864         pnfs_get_lseg(lseg);
1865         pnfs_layout_insert_lseg(lo, lseg, &free_me);
1866
1867
1868         if (res->return_on_close)
1869                 set_bit(NFS_LSEG_ROC, &lseg->pls_flags);
1870
1871         spin_unlock(&ino->i_lock);
1872         pnfs_free_lseg_list(&free_me);
1873         return lseg;
1874
1875 out_forget:
1876         spin_unlock(&ino->i_lock);
1877         lseg->pls_layout = lo;
1878         NFS_SERVER(ino)->pnfs_curr_ld->free_lseg(lseg);
1879         return ERR_PTR(-EAGAIN);
1880 }
1881
1882 static void
1883 pnfs_set_plh_return_info(struct pnfs_layout_hdr *lo, enum pnfs_iomode iomode,
1884                          u32 seq)
1885 {
1886         if (lo->plh_return_iomode != 0 && lo->plh_return_iomode != iomode)
1887                 iomode = IOMODE_ANY;
1888         lo->plh_return_iomode = iomode;
1889         set_bit(NFS_LAYOUT_RETURN_REQUESTED, &lo->plh_flags);
1890         if (seq != 0) {
1891                 WARN_ON_ONCE(lo->plh_return_seq != 0 && lo->plh_return_seq != seq);
1892                 lo->plh_return_seq = seq;
1893         }
1894 }
1895
1896 /**
1897  * pnfs_mark_matching_lsegs_return - Free or return matching layout segments
1898  * @lo: pointer to layout header
1899  * @tmp_list: list header to be used with pnfs_free_lseg_list()
1900  * @return_range: describe layout segment ranges to be returned
1901  *
1902  * This function is mainly intended for use by layoutrecall. It attempts
1903  * to free the layout segment immediately, or else to mark it for return
1904  * as soon as its reference count drops to zero.
1905  */
1906 int
1907 pnfs_mark_matching_lsegs_return(struct pnfs_layout_hdr *lo,
1908                                 struct list_head *tmp_list,
1909                                 const struct pnfs_layout_range *return_range,
1910                                 u32 seq)
1911 {
1912         struct pnfs_layout_segment *lseg, *next;
1913         int remaining = 0;
1914
1915         dprintk("%s:Begin lo %p\n", __func__, lo);
1916
1917         if (list_empty(&lo->plh_segs))
1918                 return 0;
1919
1920         assert_spin_locked(&lo->plh_inode->i_lock);
1921
1922         list_for_each_entry_safe(lseg, next, &lo->plh_segs, pls_list)
1923                 if (pnfs_match_lseg_recall(lseg, return_range, seq)) {
1924                         dprintk("%s: marking lseg %p iomode %d "
1925                                 "offset %llu length %llu\n", __func__,
1926                                 lseg, lseg->pls_range.iomode,
1927                                 lseg->pls_range.offset,
1928                                 lseg->pls_range.length);
1929                         if (mark_lseg_invalid(lseg, tmp_list))
1930                                 continue;
1931                         remaining++;
1932                         set_bit(NFS_LSEG_LAYOUTRETURN, &lseg->pls_flags);
1933                 }
1934
1935         if (remaining)
1936                 pnfs_set_plh_return_info(lo, return_range->iomode, seq);
1937
1938         return remaining;
1939 }
1940
1941 void pnfs_error_mark_layout_for_return(struct inode *inode,
1942                                        struct pnfs_layout_segment *lseg)
1943 {
1944         struct pnfs_layout_hdr *lo = NFS_I(inode)->layout;
1945         struct pnfs_layout_range range = {
1946                 .iomode = lseg->pls_range.iomode,
1947                 .offset = 0,
1948                 .length = NFS4_MAX_UINT64,
1949         };
1950         LIST_HEAD(free_me);
1951         bool return_now = false;
1952
1953         spin_lock(&inode->i_lock);
1954         pnfs_set_plh_return_info(lo, range.iomode, 0);
1955         /*
1956          * mark all matching lsegs so that we are sure to have no live
1957          * segments at hand when sending layoutreturn. See pnfs_put_lseg()
1958          * for how it works.
1959          */
1960         if (!pnfs_mark_matching_lsegs_return(lo, &free_me, &range, 0)) {
1961                 nfs4_stateid stateid;
1962                 enum pnfs_iomode iomode;
1963
1964                 return_now = pnfs_prepare_layoutreturn(lo, &stateid, &iomode);
1965                 spin_unlock(&inode->i_lock);
1966                 if (return_now)
1967                         pnfs_send_layoutreturn(lo, &stateid, iomode, false);
1968         } else {
1969                 spin_unlock(&inode->i_lock);
1970                 nfs_commit_inode(inode, 0);
1971         }
1972         pnfs_free_lseg_list(&free_me);
1973 }
1974 EXPORT_SYMBOL_GPL(pnfs_error_mark_layout_for_return);
1975
1976 void
1977 pnfs_generic_pg_init_read(struct nfs_pageio_descriptor *pgio, struct nfs_page *req)
1978 {
1979         u64 rd_size = req->wb_bytes;
1980
1981         if (pgio->pg_lseg == NULL) {
1982                 if (pgio->pg_dreq == NULL)
1983                         rd_size = i_size_read(pgio->pg_inode) - req_offset(req);
1984                 else
1985                         rd_size = nfs_dreq_bytes_left(pgio->pg_dreq);
1986
1987                 pgio->pg_lseg = pnfs_update_layout(pgio->pg_inode,
1988                                                    req->wb_context,
1989                                                    req_offset(req),
1990                                                    rd_size,
1991                                                    IOMODE_READ,
1992                                                    false,
1993                                                    GFP_KERNEL);
1994                 if (IS_ERR(pgio->pg_lseg)) {
1995                         pgio->pg_error = PTR_ERR(pgio->pg_lseg);
1996                         pgio->pg_lseg = NULL;
1997                         return;
1998                 }
1999         }
2000         /* If no lseg, fall back to read through mds */
2001         if (pgio->pg_lseg == NULL)
2002                 nfs_pageio_reset_read_mds(pgio);
2003
2004 }
2005 EXPORT_SYMBOL_GPL(pnfs_generic_pg_init_read);
2006
2007 void
2008 pnfs_generic_pg_init_write(struct nfs_pageio_descriptor *pgio,
2009                            struct nfs_page *req, u64 wb_size)
2010 {
2011         if (pgio->pg_lseg == NULL) {
2012                 pgio->pg_lseg = pnfs_update_layout(pgio->pg_inode,
2013                                                    req->wb_context,
2014                                                    req_offset(req),
2015                                                    wb_size,
2016                                                    IOMODE_RW,
2017                                                    false,
2018                                                    GFP_NOFS);
2019                 if (IS_ERR(pgio->pg_lseg)) {
2020                         pgio->pg_error = PTR_ERR(pgio->pg_lseg);
2021                         pgio->pg_lseg = NULL;
2022                         return;
2023                 }
2024         }
2025         /* If no lseg, fall back to write through mds */
2026         if (pgio->pg_lseg == NULL)
2027                 nfs_pageio_reset_write_mds(pgio);
2028 }
2029 EXPORT_SYMBOL_GPL(pnfs_generic_pg_init_write);
2030
2031 void
2032 pnfs_generic_pg_cleanup(struct nfs_pageio_descriptor *desc)
2033 {
2034         if (desc->pg_lseg) {
2035                 pnfs_put_lseg(desc->pg_lseg);
2036                 desc->pg_lseg = NULL;
2037         }
2038 }
2039 EXPORT_SYMBOL_GPL(pnfs_generic_pg_cleanup);
2040
2041 /*
2042  * Return 0 if @req cannot be coalesced into @pgio, otherwise return the number
2043  * of bytes (maximum @req->wb_bytes) that can be coalesced.
2044  */
2045 size_t
2046 pnfs_generic_pg_test(struct nfs_pageio_descriptor *pgio,
2047                      struct nfs_page *prev, struct nfs_page *req)
2048 {
2049         unsigned int size;
2050         u64 seg_end, req_start, seg_left;
2051
2052         size = nfs_generic_pg_test(pgio, prev, req);
2053         if (!size)
2054                 return 0;
2055
2056         /*
2057          * 'size' contains the number of bytes left in the current page (up
2058          * to the original size asked for in @req->wb_bytes).
2059          *
2060          * Calculate how many bytes are left in the layout segment
2061          * and if there are less bytes than 'size', return that instead.
2062          *
2063          * Please also note that 'end_offset' is actually the offset of the
2064          * first byte that lies outside the pnfs_layout_range. FIXME?
2065          *
2066          */
2067         if (pgio->pg_lseg) {
2068                 seg_end = end_offset(pgio->pg_lseg->pls_range.offset,
2069                                      pgio->pg_lseg->pls_range.length);
2070                 req_start = req_offset(req);
2071                 WARN_ON_ONCE(req_start >= seg_end);
2072                 /* start of request is past the last byte of this segment */
2073                 if (req_start >= seg_end) {
2074                         /* reference the new lseg */
2075                         if (pgio->pg_ops->pg_cleanup)
2076                                 pgio->pg_ops->pg_cleanup(pgio);
2077                         if (pgio->pg_ops->pg_init)
2078                                 pgio->pg_ops->pg_init(pgio, req);
2079                         return 0;
2080                 }
2081
2082                 /* adjust 'size' iff there are fewer bytes left in the
2083                  * segment than what nfs_generic_pg_test returned */
2084                 seg_left = seg_end - req_start;
2085                 if (seg_left < size)
2086                         size = (unsigned int)seg_left;
2087         }
2088
2089         return size;
2090 }
2091 EXPORT_SYMBOL_GPL(pnfs_generic_pg_test);
2092
2093 int pnfs_write_done_resend_to_mds(struct nfs_pgio_header *hdr)
2094 {
2095         struct nfs_pageio_descriptor pgio;
2096
2097         /* Resend all requests through the MDS */
2098         nfs_pageio_init_write(&pgio, hdr->inode, FLUSH_STABLE, true,
2099                               hdr->completion_ops);
2100         set_bit(NFS_CONTEXT_RESEND_WRITES, &hdr->args.context->flags);
2101         return nfs_pageio_resend(&pgio, hdr);
2102 }
2103 EXPORT_SYMBOL_GPL(pnfs_write_done_resend_to_mds);
2104
2105 static void pnfs_ld_handle_write_error(struct nfs_pgio_header *hdr)
2106 {
2107
2108         dprintk("pnfs write error = %d\n", hdr->pnfs_error);
2109         if (NFS_SERVER(hdr->inode)->pnfs_curr_ld->flags &
2110             PNFS_LAYOUTRET_ON_ERROR) {
2111                 pnfs_return_layout(hdr->inode);
2112         }
2113         if (!test_and_set_bit(NFS_IOHDR_REDO, &hdr->flags))
2114                 hdr->task.tk_status = pnfs_write_done_resend_to_mds(hdr);
2115 }
2116
2117 /*
2118  * Called by non rpc-based layout drivers
2119  */
2120 void pnfs_ld_write_done(struct nfs_pgio_header *hdr)
2121 {
2122         if (likely(!hdr->pnfs_error)) {
2123                 pnfs_set_layoutcommit(hdr->inode, hdr->lseg,
2124                                 hdr->mds_offset + hdr->res.count);
2125                 hdr->mds_ops->rpc_call_done(&hdr->task, hdr);
2126         }
2127         trace_nfs4_pnfs_write(hdr, hdr->pnfs_error);
2128         if (unlikely(hdr->pnfs_error))
2129                 pnfs_ld_handle_write_error(hdr);
2130         hdr->mds_ops->rpc_release(hdr);
2131 }
2132 EXPORT_SYMBOL_GPL(pnfs_ld_write_done);
2133
2134 static void
2135 pnfs_write_through_mds(struct nfs_pageio_descriptor *desc,
2136                 struct nfs_pgio_header *hdr)
2137 {
2138         struct nfs_pgio_mirror *mirror = nfs_pgio_current_mirror(desc);
2139
2140         if (!test_and_set_bit(NFS_IOHDR_REDO, &hdr->flags)) {
2141                 list_splice_tail_init(&hdr->pages, &mirror->pg_list);
2142                 nfs_pageio_reset_write_mds(desc);
2143                 mirror->pg_recoalesce = 1;
2144         }
2145         hdr->completion_ops->completion(hdr);
2146 }
2147
2148 static enum pnfs_try_status
2149 pnfs_try_to_write_data(struct nfs_pgio_header *hdr,
2150                         const struct rpc_call_ops *call_ops,
2151                         struct pnfs_layout_segment *lseg,
2152                         int how)
2153 {
2154         struct inode *inode = hdr->inode;
2155         enum pnfs_try_status trypnfs;
2156         struct nfs_server *nfss = NFS_SERVER(inode);
2157
2158         hdr->mds_ops = call_ops;
2159
2160         dprintk("%s: Writing ino:%lu %u@%llu (how %d)\n", __func__,
2161                 inode->i_ino, hdr->args.count, hdr->args.offset, how);
2162         trypnfs = nfss->pnfs_curr_ld->write_pagelist(hdr, how);
2163         if (trypnfs != PNFS_NOT_ATTEMPTED)
2164                 nfs_inc_stats(inode, NFSIOS_PNFS_WRITE);
2165         dprintk("%s End (trypnfs:%d)\n", __func__, trypnfs);
2166         return trypnfs;
2167 }
2168
2169 static void
2170 pnfs_do_write(struct nfs_pageio_descriptor *desc,
2171               struct nfs_pgio_header *hdr, int how)
2172 {
2173         const struct rpc_call_ops *call_ops = desc->pg_rpc_callops;
2174         struct pnfs_layout_segment *lseg = desc->pg_lseg;
2175         enum pnfs_try_status trypnfs;
2176
2177         trypnfs = pnfs_try_to_write_data(hdr, call_ops, lseg, how);
2178         if (trypnfs == PNFS_NOT_ATTEMPTED)
2179                 pnfs_write_through_mds(desc, hdr);
2180 }
2181
2182 static void pnfs_writehdr_free(struct nfs_pgio_header *hdr)
2183 {
2184         pnfs_put_lseg(hdr->lseg);
2185         nfs_pgio_header_free(hdr);
2186 }
2187
2188 int
2189 pnfs_generic_pg_writepages(struct nfs_pageio_descriptor *desc)
2190 {
2191         struct nfs_pgio_header *hdr;
2192         int ret;
2193
2194         hdr = nfs_pgio_header_alloc(desc->pg_rw_ops);
2195         if (!hdr) {
2196                 desc->pg_error = -ENOMEM;
2197                 return desc->pg_error;
2198         }
2199         nfs_pgheader_init(desc, hdr, pnfs_writehdr_free);
2200
2201         hdr->lseg = pnfs_get_lseg(desc->pg_lseg);
2202         ret = nfs_generic_pgio(desc, hdr);
2203         if (!ret)
2204                 pnfs_do_write(desc, hdr, desc->pg_ioflags);
2205
2206         return ret;
2207 }
2208 EXPORT_SYMBOL_GPL(pnfs_generic_pg_writepages);
2209
2210 int pnfs_read_done_resend_to_mds(struct nfs_pgio_header *hdr)
2211 {
2212         struct nfs_pageio_descriptor pgio;
2213
2214         /* Resend all requests through the MDS */
2215         nfs_pageio_init_read(&pgio, hdr->inode, true, hdr->completion_ops);
2216         return nfs_pageio_resend(&pgio, hdr);
2217 }
2218 EXPORT_SYMBOL_GPL(pnfs_read_done_resend_to_mds);
2219
2220 static void pnfs_ld_handle_read_error(struct nfs_pgio_header *hdr)
2221 {
2222         dprintk("pnfs read error = %d\n", hdr->pnfs_error);
2223         if (NFS_SERVER(hdr->inode)->pnfs_curr_ld->flags &
2224             PNFS_LAYOUTRET_ON_ERROR) {
2225                 pnfs_return_layout(hdr->inode);
2226         }
2227         if (!test_and_set_bit(NFS_IOHDR_REDO, &hdr->flags))
2228                 hdr->task.tk_status = pnfs_read_done_resend_to_mds(hdr);
2229 }
2230
2231 /*
2232  * Called by non rpc-based layout drivers
2233  */
2234 void pnfs_ld_read_done(struct nfs_pgio_header *hdr)
2235 {
2236         if (likely(!hdr->pnfs_error))
2237                 hdr->mds_ops->rpc_call_done(&hdr->task, hdr);
2238         trace_nfs4_pnfs_read(hdr, hdr->pnfs_error);
2239         if (unlikely(hdr->pnfs_error))
2240                 pnfs_ld_handle_read_error(hdr);
2241         hdr->mds_ops->rpc_release(hdr);
2242 }
2243 EXPORT_SYMBOL_GPL(pnfs_ld_read_done);
2244
2245 static void
2246 pnfs_read_through_mds(struct nfs_pageio_descriptor *desc,
2247                 struct nfs_pgio_header *hdr)
2248 {
2249         struct nfs_pgio_mirror *mirror = nfs_pgio_current_mirror(desc);
2250
2251         if (!test_and_set_bit(NFS_IOHDR_REDO, &hdr->flags)) {
2252                 list_splice_tail_init(&hdr->pages, &mirror->pg_list);
2253                 nfs_pageio_reset_read_mds(desc);
2254                 mirror->pg_recoalesce = 1;
2255         }
2256         hdr->completion_ops->completion(hdr);
2257 }
2258
2259 /*
2260  * Call the appropriate parallel I/O subsystem read function.
2261  */
2262 static enum pnfs_try_status
2263 pnfs_try_to_read_data(struct nfs_pgio_header *hdr,
2264                        const struct rpc_call_ops *call_ops,
2265                        struct pnfs_layout_segment *lseg)
2266 {
2267         struct inode *inode = hdr->inode;
2268         struct nfs_server *nfss = NFS_SERVER(inode);
2269         enum pnfs_try_status trypnfs;
2270
2271         hdr->mds_ops = call_ops;
2272
2273         dprintk("%s: Reading ino:%lu %u@%llu\n",
2274                 __func__, inode->i_ino, hdr->args.count, hdr->args.offset);
2275
2276         trypnfs = nfss->pnfs_curr_ld->read_pagelist(hdr);
2277         if (trypnfs != PNFS_NOT_ATTEMPTED)
2278                 nfs_inc_stats(inode, NFSIOS_PNFS_READ);
2279         dprintk("%s End (trypnfs:%d)\n", __func__, trypnfs);
2280         return trypnfs;
2281 }
2282
2283 /* Resend all requests through pnfs. */
2284 void pnfs_read_resend_pnfs(struct nfs_pgio_header *hdr)
2285 {
2286         struct nfs_pageio_descriptor pgio;
2287
2288         if (!test_and_set_bit(NFS_IOHDR_REDO, &hdr->flags)) {
2289                 /* Prevent deadlocks with layoutreturn! */
2290                 pnfs_put_lseg(hdr->lseg);
2291                 hdr->lseg = NULL;
2292
2293                 nfs_pageio_init_read(&pgio, hdr->inode, false,
2294                                         hdr->completion_ops);
2295                 hdr->task.tk_status = nfs_pageio_resend(&pgio, hdr);
2296         }
2297 }
2298 EXPORT_SYMBOL_GPL(pnfs_read_resend_pnfs);
2299
2300 static void
2301 pnfs_do_read(struct nfs_pageio_descriptor *desc, struct nfs_pgio_header *hdr)
2302 {
2303         const struct rpc_call_ops *call_ops = desc->pg_rpc_callops;
2304         struct pnfs_layout_segment *lseg = desc->pg_lseg;
2305         enum pnfs_try_status trypnfs;
2306
2307         trypnfs = pnfs_try_to_read_data(hdr, call_ops, lseg);
2308         switch (trypnfs) {
2309         case PNFS_NOT_ATTEMPTED:
2310                 pnfs_read_through_mds(desc, hdr);
2311         case PNFS_ATTEMPTED:
2312                 break;
2313         case PNFS_TRY_AGAIN:
2314                 /* cleanup hdr and prepare to redo pnfs */
2315                 if (!test_and_set_bit(NFS_IOHDR_REDO, &hdr->flags)) {
2316                         struct nfs_pgio_mirror *mirror = nfs_pgio_current_mirror(desc);
2317                         list_splice_init(&hdr->pages, &mirror->pg_list);
2318                         mirror->pg_recoalesce = 1;
2319                 }
2320                 hdr->mds_ops->rpc_release(hdr);
2321         }
2322 }
2323
2324 static void pnfs_readhdr_free(struct nfs_pgio_header *hdr)
2325 {
2326         pnfs_put_lseg(hdr->lseg);
2327         nfs_pgio_header_free(hdr);
2328 }
2329
2330 int
2331 pnfs_generic_pg_readpages(struct nfs_pageio_descriptor *desc)
2332 {
2333         struct nfs_pgio_header *hdr;
2334         int ret;
2335
2336         hdr = nfs_pgio_header_alloc(desc->pg_rw_ops);
2337         if (!hdr) {
2338                 desc->pg_error = -ENOMEM;
2339                 return desc->pg_error;
2340         }
2341         nfs_pgheader_init(desc, hdr, pnfs_readhdr_free);
2342         hdr->lseg = pnfs_get_lseg(desc->pg_lseg);
2343         ret = nfs_generic_pgio(desc, hdr);
2344         if (!ret)
2345                 pnfs_do_read(desc, hdr);
2346         return ret;
2347 }
2348 EXPORT_SYMBOL_GPL(pnfs_generic_pg_readpages);
2349
2350 static void pnfs_clear_layoutcommitting(struct inode *inode)
2351 {
2352         unsigned long *bitlock = &NFS_I(inode)->flags;
2353
2354         clear_bit_unlock(NFS_INO_LAYOUTCOMMITTING, bitlock);
2355         smp_mb__after_atomic();
2356         wake_up_bit(bitlock, NFS_INO_LAYOUTCOMMITTING);
2357 }
2358
2359 /*
2360  * There can be multiple RW segments.
2361  */
2362 static void pnfs_list_write_lseg(struct inode *inode, struct list_head *listp)
2363 {
2364         struct pnfs_layout_segment *lseg;
2365
2366         list_for_each_entry(lseg, &NFS_I(inode)->layout->plh_segs, pls_list) {
2367                 if (lseg->pls_range.iomode == IOMODE_RW &&
2368                     test_and_clear_bit(NFS_LSEG_LAYOUTCOMMIT, &lseg->pls_flags))
2369                         list_add(&lseg->pls_lc_list, listp);
2370         }
2371 }
2372
2373 static void pnfs_list_write_lseg_done(struct inode *inode, struct list_head *listp)
2374 {
2375         struct pnfs_layout_segment *lseg, *tmp;
2376
2377         /* Matched by references in pnfs_set_layoutcommit */
2378         list_for_each_entry_safe(lseg, tmp, listp, pls_lc_list) {
2379                 list_del_init(&lseg->pls_lc_list);
2380                 pnfs_put_lseg(lseg);
2381         }
2382
2383         pnfs_clear_layoutcommitting(inode);
2384 }
2385
2386 void pnfs_set_lo_fail(struct pnfs_layout_segment *lseg)
2387 {
2388         pnfs_layout_io_set_failed(lseg->pls_layout, lseg->pls_range.iomode);
2389 }
2390 EXPORT_SYMBOL_GPL(pnfs_set_lo_fail);
2391
2392 void
2393 pnfs_set_layoutcommit(struct inode *inode, struct pnfs_layout_segment *lseg,
2394                 loff_t end_pos)
2395 {
2396         struct nfs_inode *nfsi = NFS_I(inode);
2397         bool mark_as_dirty = false;
2398
2399         spin_lock(&inode->i_lock);
2400         if (!test_and_set_bit(NFS_INO_LAYOUTCOMMIT, &nfsi->flags)) {
2401                 nfsi->layout->plh_lwb = end_pos;
2402                 mark_as_dirty = true;
2403                 dprintk("%s: Set layoutcommit for inode %lu ",
2404                         __func__, inode->i_ino);
2405         } else if (end_pos > nfsi->layout->plh_lwb)
2406                 nfsi->layout->plh_lwb = end_pos;
2407         if (!test_and_set_bit(NFS_LSEG_LAYOUTCOMMIT, &lseg->pls_flags)) {
2408                 /* references matched in nfs4_layoutcommit_release */
2409                 pnfs_get_lseg(lseg);
2410         }
2411         spin_unlock(&inode->i_lock);
2412         dprintk("%s: lseg %p end_pos %llu\n",
2413                 __func__, lseg, nfsi->layout->plh_lwb);
2414
2415         /* if pnfs_layoutcommit_inode() runs between inode locks, the next one
2416          * will be a noop because NFS_INO_LAYOUTCOMMIT will not be set */
2417         if (mark_as_dirty)
2418                 mark_inode_dirty_sync(inode);
2419 }
2420 EXPORT_SYMBOL_GPL(pnfs_set_layoutcommit);
2421
2422 void pnfs_cleanup_layoutcommit(struct nfs4_layoutcommit_data *data)
2423 {
2424         struct nfs_server *nfss = NFS_SERVER(data->args.inode);
2425
2426         if (nfss->pnfs_curr_ld->cleanup_layoutcommit)
2427                 nfss->pnfs_curr_ld->cleanup_layoutcommit(data);
2428         pnfs_list_write_lseg_done(data->args.inode, &data->lseg_list);
2429 }
2430
2431 /*
2432  * For the LAYOUT4_NFSV4_1_FILES layout type, NFS_DATA_SYNC WRITEs and
2433  * NFS_UNSTABLE WRITEs with a COMMIT to data servers must store enough
2434  * data to disk to allow the server to recover the data if it crashes.
2435  * LAYOUTCOMMIT is only needed when the NFL4_UFLG_COMMIT_THRU_MDS flag
2436  * is off, and a COMMIT is sent to a data server, or
2437  * if WRITEs to a data server return NFS_DATA_SYNC.
2438  */
2439 int
2440 pnfs_layoutcommit_inode(struct inode *inode, bool sync)
2441 {
2442         struct pnfs_layoutdriver_type *ld = NFS_SERVER(inode)->pnfs_curr_ld;
2443         struct nfs4_layoutcommit_data *data;
2444         struct nfs_inode *nfsi = NFS_I(inode);
2445         loff_t end_pos;
2446         int status;
2447
2448         if (!pnfs_layoutcommit_outstanding(inode))
2449                 return 0;
2450
2451         dprintk("--> %s inode %lu\n", __func__, inode->i_ino);
2452
2453         status = -EAGAIN;
2454         if (test_and_set_bit(NFS_INO_LAYOUTCOMMITTING, &nfsi->flags)) {
2455                 if (!sync)
2456                         goto out;
2457                 status = wait_on_bit_lock_action(&nfsi->flags,
2458                                 NFS_INO_LAYOUTCOMMITTING,
2459                                 nfs_wait_bit_killable,
2460                                 TASK_KILLABLE);
2461                 if (status)
2462                         goto out;
2463         }
2464
2465         status = -ENOMEM;
2466         /* Note kzalloc ensures data->res.seq_res.sr_slot == NULL */
2467         data = kzalloc(sizeof(*data), GFP_NOFS);
2468         if (!data)
2469                 goto clear_layoutcommitting;
2470
2471         status = 0;
2472         spin_lock(&inode->i_lock);
2473         if (!test_and_clear_bit(NFS_INO_LAYOUTCOMMIT, &nfsi->flags))
2474                 goto out_unlock;
2475
2476         INIT_LIST_HEAD(&data->lseg_list);
2477         pnfs_list_write_lseg(inode, &data->lseg_list);
2478
2479         end_pos = nfsi->layout->plh_lwb;
2480
2481         nfs4_stateid_copy(&data->args.stateid, &nfsi->layout->plh_stateid);
2482         spin_unlock(&inode->i_lock);
2483
2484         data->args.inode = inode;
2485         data->cred = get_rpccred(nfsi->layout->plh_lc_cred);
2486         nfs_fattr_init(&data->fattr);
2487         data->args.bitmask = NFS_SERVER(inode)->cache_consistency_bitmask;
2488         data->res.fattr = &data->fattr;
2489         if (end_pos != 0)
2490                 data->args.lastbytewritten = end_pos - 1;
2491         else
2492                 data->args.lastbytewritten = U64_MAX;
2493         data->res.server = NFS_SERVER(inode);
2494
2495         if (ld->prepare_layoutcommit) {
2496                 status = ld->prepare_layoutcommit(&data->args);
2497                 if (status) {
2498                         put_rpccred(data->cred);
2499                         spin_lock(&inode->i_lock);
2500                         set_bit(NFS_INO_LAYOUTCOMMIT, &nfsi->flags);
2501                         if (end_pos > nfsi->layout->plh_lwb)
2502                                 nfsi->layout->plh_lwb = end_pos;
2503                         goto out_unlock;
2504                 }
2505         }
2506
2507
2508         status = nfs4_proc_layoutcommit(data, sync);
2509 out:
2510         if (status)
2511                 mark_inode_dirty_sync(inode);
2512         dprintk("<-- %s status %d\n", __func__, status);
2513         return status;
2514 out_unlock:
2515         spin_unlock(&inode->i_lock);
2516         kfree(data);
2517 clear_layoutcommitting:
2518         pnfs_clear_layoutcommitting(inode);
2519         goto out;
2520 }
2521 EXPORT_SYMBOL_GPL(pnfs_layoutcommit_inode);
2522
2523 int
2524 pnfs_generic_sync(struct inode *inode, bool datasync)
2525 {
2526         return pnfs_layoutcommit_inode(inode, true);
2527 }
2528 EXPORT_SYMBOL_GPL(pnfs_generic_sync);
2529
2530 struct nfs4_threshold *pnfs_mdsthreshold_alloc(void)
2531 {
2532         struct nfs4_threshold *thp;
2533
2534         thp = kzalloc(sizeof(*thp), GFP_NOFS);
2535         if (!thp) {
2536                 dprintk("%s mdsthreshold allocation failed\n", __func__);
2537                 return NULL;
2538         }
2539         return thp;
2540 }
2541
2542 #if IS_ENABLED(CONFIG_NFS_V4_2)
2543 int
2544 pnfs_report_layoutstat(struct inode *inode, gfp_t gfp_flags)
2545 {
2546         struct pnfs_layoutdriver_type *ld = NFS_SERVER(inode)->pnfs_curr_ld;
2547         struct nfs_server *server = NFS_SERVER(inode);
2548         struct nfs_inode *nfsi = NFS_I(inode);
2549         struct nfs42_layoutstat_data *data;
2550         struct pnfs_layout_hdr *hdr;
2551         int status = 0;
2552
2553         if (!pnfs_enabled_sb(server) || !ld->prepare_layoutstats)
2554                 goto out;
2555
2556         if (!nfs_server_capable(inode, NFS_CAP_LAYOUTSTATS))
2557                 goto out;
2558
2559         if (test_and_set_bit(NFS_INO_LAYOUTSTATS, &nfsi->flags))
2560                 goto out;
2561
2562         spin_lock(&inode->i_lock);
2563         if (!NFS_I(inode)->layout) {
2564                 spin_unlock(&inode->i_lock);
2565                 goto out_clear_layoutstats;
2566         }
2567         hdr = NFS_I(inode)->layout;
2568         pnfs_get_layout_hdr(hdr);
2569         spin_unlock(&inode->i_lock);
2570
2571         data = kzalloc(sizeof(*data), gfp_flags);
2572         if (!data) {
2573                 status = -ENOMEM;
2574                 goto out_put;
2575         }
2576
2577         data->args.fh = NFS_FH(inode);
2578         data->args.inode = inode;
2579         status = ld->prepare_layoutstats(&data->args);
2580         if (status)
2581                 goto out_free;
2582
2583         status = nfs42_proc_layoutstats_generic(NFS_SERVER(inode), data);
2584
2585 out:
2586         dprintk("%s returns %d\n", __func__, status);
2587         return status;
2588
2589 out_free:
2590         kfree(data);
2591 out_put:
2592         pnfs_put_layout_hdr(hdr);
2593 out_clear_layoutstats:
2594         smp_mb__before_atomic();
2595         clear_bit(NFS_INO_LAYOUTSTATS, &nfsi->flags);
2596         smp_mb__after_atomic();
2597         goto out;
2598 }
2599 EXPORT_SYMBOL_GPL(pnfs_report_layoutstat);
2600 #endif
2601
2602 unsigned int layoutstats_timer;
2603 module_param(layoutstats_timer, uint, 0644);
2604 EXPORT_SYMBOL_GPL(layoutstats_timer);