Whamcloud - gitweb
b=21122 fix a race between page fault and lock cancel.
[fs/lustre-release.git] / lustre / obdclass / cl_page.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
30  * Use is subject to license terms.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * Client Lustre Page.
37  *
38  *   Author: Nikita Danilov <nikita.danilov@sun.com>
39  */
40
41 #define DEBUG_SUBSYSTEM S_CLASS
42 #ifndef EXPORT_SYMTAB
43 # define EXPORT_SYMTAB
44 #endif
45
46 #include <libcfs/libcfs.h>
47 #include <obd_class.h>
48 #include <obd_support.h>
49 #include <libcfs/list.h>
50
51 #include <cl_object.h>
52 #include "cl_internal.h"
53
54 static void cl_page_delete0(const struct lu_env *env, struct cl_page *pg,
55                             int radix);
56
57 static cfs_mem_cache_t      *cl_page_kmem = NULL;
58
59 static struct lu_kmem_descr cl_page_caches[] = {
60         {
61                 .ckd_cache = &cl_page_kmem,
62                 .ckd_name  = "cl_page_kmem",
63                 .ckd_size  = sizeof (struct cl_page)
64         },
65         {
66                 .ckd_cache = NULL
67         }
68 };
69
70 #ifdef LIBCFS_DEBUG
71 # define PASSERT(env, page, expr)                                       \
72   do {                                                                    \
73           if (unlikely(!(expr))) {                                      \
74                   CL_PAGE_DEBUG(D_ERROR, (env), (page), #expr "\n");    \
75                   LASSERT(0);                                           \
76           }                                                             \
77   } while (0)
78 #else /* !LIBCFS_DEBUG */
79 # define PASSERT(env, page, exp) \
80         ((void)sizeof(env), (void)sizeof(page), (void)sizeof !!(exp))
81 #endif /* !LIBCFS_DEBUG */
82
83 #ifdef INVARIANT_CHECK
84 # define PINVRNT(env, page, expr)                                       \
85   do {                                                                    \
86           if (unlikely(!(expr))) {                                      \
87                   CL_PAGE_DEBUG(D_ERROR, (env), (page), #expr "\n");    \
88                   LINVRNT(0);                                           \
89           }                                                             \
90   } while (0)
91 #else /* !INVARIANT_CHECK */
92 # define PINVRNT(env, page, exp) \
93         ((void)sizeof(env), (void)sizeof(page), (void)sizeof !!(exp))
94 #endif /* !INVARIANT_CHECK */
95
96 /**
97  * Internal version of cl_page_top, it should be called with page referenced,
98  * or coh_page_guard held.
99  */
100 static struct cl_page *cl_page_top_trusted(struct cl_page *page)
101 {
102         while (page->cp_parent != NULL)
103                 page = page->cp_parent;
104         return page;
105 }
106
107 /**
108  * Internal version of cl_page_get().
109  *
110  * This function can be used to obtain initial reference to previously
111  * unreferenced cached object. It can be called only if concurrent page
112  * reclamation is somehow prevented, e.g., by locking page radix-tree
113  * (cl_object_header::hdr->coh_page_guard), or by keeping a lock on a VM page,
114  * associated with \a page.
115  *
116  * Use with care! Not exported.
117  */
118 static void cl_page_get_trust(struct cl_page *page)
119 {
120         /*
121          * Checkless version for trusted users.
122          */
123         if (cfs_atomic_inc_return(&page->cp_ref) == 1)
124                 cfs_atomic_inc(&cl_object_site(page->cp_obj)->cs_pages.cs_busy);
125 }
126
127 /**
128  * Returns a slice within a page, corresponding to the given layer in the
129  * device stack.
130  *
131  * \see cl_lock_at()
132  */
133 static const struct cl_page_slice *
134 cl_page_at_trusted(const struct cl_page *page,
135                    const struct lu_device_type *dtype)
136 {
137         const struct cl_page_slice *slice;
138
139 #ifdef INVARIANT_CHECK
140         struct cl_object_header *ch = cl_object_header(page->cp_obj);
141
142         if (!cfs_atomic_read(&page->cp_ref))
143                 LASSERT_SPIN_LOCKED(&ch->coh_page_guard);
144 #endif
145         ENTRY;
146
147         page = cl_page_top_trusted((struct cl_page *)page);
148         do {
149                 cfs_list_for_each_entry(slice, &page->cp_layers, cpl_linkage) {
150                         if (slice->cpl_obj->co_lu.lo_dev->ld_type == dtype)
151                                 RETURN(slice);
152                 }
153                 page = page->cp_child;
154         } while (page != NULL);
155         RETURN(NULL);
156 }
157
158 /**
159  * Returns a page with given index in the given object, or NULL if no page is
160  * found. Acquires a reference on \a page.
161  *
162  * Locking: called under cl_object_header::coh_page_guard spin-lock.
163  */
164 struct cl_page *cl_page_lookup(struct cl_object_header *hdr, pgoff_t index)
165 {
166         struct cl_page *page;
167
168         LASSERT_SPIN_LOCKED(&hdr->coh_page_guard);
169
170         page = radix_tree_lookup(&hdr->coh_tree, index);
171         if (page != NULL) {
172                 cl_page_get_trust(page);
173         }
174         return page;
175 }
176 EXPORT_SYMBOL(cl_page_lookup);
177
178 /**
179  * Returns a list of pages by a given [start, end] of \a obj.
180  *
181  * \param resched If not NULL, then we give up before hogging CPU for too
182  * long and set *resched = 1, in that case caller should implement a retry
183  * logic.
184  *
185  * Gang tree lookup (radix_tree_gang_lookup()) optimization is absolutely
186  * crucial in the face of [offset, EOF] locks.
187  */
188 void cl_page_gang_lookup(const struct lu_env *env, struct cl_object *obj,
189                          struct cl_io *io, pgoff_t start, pgoff_t end,
190                          struct cl_page_list *queue, int nonblock,
191                          int *resched)
192 {
193         struct cl_object_header *hdr;
194         struct cl_page          *page;
195         struct cl_page         **pvec;
196         const struct cl_page_slice  *slice;
197         const struct lu_device_type *dtype;
198         pgoff_t                  idx;
199         unsigned int             nr;
200         unsigned int             i;
201         unsigned int             j;
202         int                    (*page_own)(const struct lu_env *env,
203                                            struct cl_io *io,
204                                            struct cl_page *pg);
205         ENTRY;
206
207         if (resched != NULL)
208                 *resched = 0;
209         page_own = nonblock ? cl_page_own_try : cl_page_own;
210
211         idx = start;
212         hdr = cl_object_header(obj);
213         pvec = cl_env_info(env)->clt_pvec;
214         dtype = cl_object_top(obj)->co_lu.lo_dev->ld_type;
215         cfs_spin_lock(&hdr->coh_page_guard);
216         while ((nr = radix_tree_gang_lookup(&hdr->coh_tree, (void **)pvec,
217                                             idx, CLT_PVEC_SIZE)) > 0) {
218                 idx = pvec[nr - 1]->cp_index + 1;
219                 for (i = 0, j = 0; i < nr; ++i) {
220                         page = pvec[i];
221                         pvec[i] = NULL;
222                         if (page->cp_index > end)
223                                 break;
224                         if (page->cp_state == CPS_FREEING)
225                                 continue;
226                         if (page->cp_type == CPT_TRANSIENT) {
227                                 /* God, we found a transient page!*/
228                                 continue;
229                         }
230
231                         slice = cl_page_at_trusted(page, dtype);
232                         /*
233                          * Pages for lsm-less file has no underneath sub-page
234                          * for osc, in case of ...
235                          */
236                         PASSERT(env, page, slice != NULL);
237
238                         page = slice->cpl_page;
239                         /*
240                          * Can safely call cl_page_get_trust() under
241                          * radix-tree spin-lock.
242                          *
243                          * XXX not true, because @page is from object another
244                          * than @hdr and protected by different tree lock.
245                          */
246                         cl_page_get_trust(page);
247                         lu_ref_add_atomic(&page->cp_reference,
248                                           "page_list", cfs_current());
249                         pvec[j++] = page;
250                 }
251
252                 /*
253                  * Here a delicate locking dance is performed. Current thread
254                  * holds a reference to a page, but has to own it before it
255                  * can be placed into queue. Owning implies waiting, so
256                  * radix-tree lock is to be released. After a wait one has to
257                  * check that pages weren't truncated (cl_page_own() returns
258                  * error in the latter case).
259                  */
260                 cfs_spin_unlock(&hdr->coh_page_guard);
261                 for (i = 0; i < j; ++i) {
262                         page = pvec[i];
263                         if (page_own(env, io, page) == 0)
264                                 cl_page_list_add(queue, page);
265                         lu_ref_del(&page->cp_reference,
266                                    "page_list", cfs_current());
267                         cl_page_put(env, page);
268                 }
269                 cfs_spin_lock(&hdr->coh_page_guard);
270                 if (nr < CLT_PVEC_SIZE)
271                         break;
272                 if (resched != NULL && cfs_need_resched()) {
273                         *resched = 1;
274                         break;
275                 }
276         }
277         cfs_spin_unlock(&hdr->coh_page_guard);
278         EXIT;
279 }
280 EXPORT_SYMBOL(cl_page_gang_lookup);
281
282 static void cl_page_free(const struct lu_env *env, struct cl_page *page)
283 {
284         struct cl_object *obj  = page->cp_obj;
285         struct cl_site   *site = cl_object_site(obj);
286
287         PASSERT(env, page, cfs_list_empty(&page->cp_batch));
288         PASSERT(env, page, page->cp_owner == NULL);
289         PASSERT(env, page, page->cp_req == NULL);
290         PASSERT(env, page, page->cp_parent == NULL);
291         PASSERT(env, page, page->cp_state == CPS_FREEING);
292
293         ENTRY;
294         cfs_might_sleep();
295         while (!cfs_list_empty(&page->cp_layers)) {
296                 struct cl_page_slice *slice;
297
298                 slice = cfs_list_entry(page->cp_layers.next,
299                                        struct cl_page_slice, cpl_linkage);
300                 cfs_list_del_init(page->cp_layers.next);
301                 slice->cpl_ops->cpo_fini(env, slice);
302         }
303         cfs_atomic_dec(&site->cs_pages.cs_total);
304
305 #ifdef LUSTRE_PAGESTATE_TRACKING
306         cfs_atomic_dec(&site->cs_pages_state[page->cp_state]);
307 #endif
308         lu_object_ref_del_at(&obj->co_lu, page->cp_obj_ref, "cl_page", page);
309         cl_object_put(env, obj);
310         lu_ref_fini(&page->cp_reference);
311         OBD_SLAB_FREE_PTR(page, cl_page_kmem);
312         EXIT;
313 }
314
315 /**
316  * Helper function updating page state. This is the only place in the code
317  * where cl_page::cp_state field is mutated.
318  */
319 static inline void cl_page_state_set_trust(struct cl_page *page,
320                                            enum cl_page_state state)
321 {
322         /* bypass const. */
323         *(enum cl_page_state *)&page->cp_state = state;
324 }
325
326 static int cl_page_alloc(const struct lu_env *env, struct cl_object *o,
327                          pgoff_t ind, struct page *vmpage,
328                          enum cl_page_type type, struct cl_page **out)
329 {
330         struct cl_page          *page;
331         struct cl_page          *err  = NULL;
332         struct lu_object_header *head;
333         struct cl_site          *site = cl_object_site(o);
334         int                      result;
335
336         ENTRY;
337         result = +1;
338         OBD_SLAB_ALLOC_PTR_GFP(page, cl_page_kmem, CFS_ALLOC_IO);
339         if (page != NULL) {
340                 cfs_atomic_set(&page->cp_ref, 1);
341                 page->cp_obj = o;
342                 cl_object_get(o);
343                 page->cp_obj_ref = lu_object_ref_add(&o->co_lu,
344                                                      "cl_page", page);
345                 page->cp_index = ind;
346                 cl_page_state_set_trust(page, CPS_CACHED);
347                 page->cp_type = type;
348                 CFS_INIT_LIST_HEAD(&page->cp_layers);
349                 CFS_INIT_LIST_HEAD(&page->cp_batch);
350                 CFS_INIT_LIST_HEAD(&page->cp_flight);
351                 cfs_mutex_init(&page->cp_mutex);
352                 lu_ref_init(&page->cp_reference);
353                 head = o->co_lu.lo_header;
354                 cfs_list_for_each_entry(o, &head->loh_layers,
355                                         co_lu.lo_linkage) {
356                         if (o->co_ops->coo_page_init != NULL) {
357                                 err = o->co_ops->coo_page_init(env, o,
358                                                                page, vmpage);
359                                 if (err != NULL) {
360                                         cl_page_state_set_trust(page,
361                                                                 CPS_FREEING);
362                                         cl_page_free(env, page);
363                                         page = err;
364                                         break;
365                                 }
366                         }
367                 }
368                 if (err == NULL) {
369                         cfs_atomic_inc(&site->cs_pages.cs_busy);
370                         cfs_atomic_inc(&site->cs_pages.cs_total);
371
372 #ifdef LUSTRE_PAGESTATE_TRACKING
373                         cfs_atomic_inc(&site->cs_pages_state[CPS_CACHED]);
374 #endif
375                         cfs_atomic_inc(&site->cs_pages.cs_created);
376                         result = 0;
377                 }
378         } else
379                 page = ERR_PTR(-ENOMEM);
380         *out = page;
381         RETURN(result);
382 }
383
384 /**
385  * Returns a cl_page with index \a idx at the object \a o, and associated with
386  * the VM page \a vmpage.
387  *
388  * This is the main entry point into the cl_page caching interface. First, a
389  * cache (implemented as a per-object radix tree) is consulted. If page is
390  * found there, it is returned immediately. Otherwise new page is allocated
391  * and returned. In any case, additional reference to page is acquired.
392  *
393  * \see cl_object_find(), cl_lock_find()
394  */
395 static struct cl_page *cl_page_find0(const struct lu_env *env,
396                                      struct cl_object *o,
397                                      pgoff_t idx, struct page *vmpage,
398                                      enum cl_page_type type,
399                                      struct cl_page *parent)
400 {
401         struct cl_page          *page;
402         struct cl_page          *ghost = NULL;
403         struct cl_object_header *hdr;
404         struct cl_site          *site = cl_object_site(o);
405         int err;
406
407         LINVRNT(type == CPT_CACHEABLE || type == CPT_TRANSIENT);
408         cfs_might_sleep();
409
410         ENTRY;
411
412         hdr = cl_object_header(o);
413         cfs_atomic_inc(&site->cs_pages.cs_lookup);
414
415         CDEBUG(D_PAGE, "%lu@"DFID" %p %lx %d\n",
416                idx, PFID(&hdr->coh_lu.loh_fid), vmpage, vmpage->private, type);
417         /* fast path. */
418         if (type == CPT_CACHEABLE) {
419                 /*
420                  * cl_vmpage_page() can be called here without any locks as
421                  *
422                  *     - "vmpage" is locked (which prevents ->private from
423                  *       concurrent updates), and
424                  *
425                  *     - "o" cannot be destroyed while current thread holds a
426                  *       reference on it.
427                  */
428                 page = cl_vmpage_page(vmpage, o);
429                 PINVRNT(env, page,
430                         ergo(page != NULL,
431                              cl_page_vmpage(env, page) == vmpage &&
432                              (void *)radix_tree_lookup(&hdr->coh_tree,
433                                                        idx) == page));
434         } else {
435                 cfs_spin_lock(&hdr->coh_page_guard);
436                 page = cl_page_lookup(hdr, idx);
437                 cfs_spin_unlock(&hdr->coh_page_guard);
438         }
439         if (page != NULL) {
440                 cfs_atomic_inc(&site->cs_pages.cs_hit);
441                 RETURN(page);
442         }
443
444         /* allocate and initialize cl_page */
445         err = cl_page_alloc(env, o, idx, vmpage, type, &page);
446         if (err != 0)
447                 RETURN(page);
448         /*
449          * XXX optimization: use radix_tree_preload() here, and change tree
450          * gfp mask to GFP_KERNEL in cl_object_header_init().
451          */
452         cfs_spin_lock(&hdr->coh_page_guard);
453         err = radix_tree_insert(&hdr->coh_tree, idx, page);
454         if (err != 0) {
455                 ghost = page;
456                 /*
457                  * Noted by Jay: a lock on \a vmpage protects cl_page_find()
458                  * from this race, but
459                  *
460                  *     0. it's better to have cl_page interface "locally
461                  *     consistent" so that its correctness can be reasoned
462                  *     about without appealing to the (obscure world of) VM
463                  *     locking.
464                  *
465                  *     1. handling this race allows ->coh_tree to remain
466                  *     consistent even when VM locking is somehow busted,
467                  *     which is very useful during diagnosing and debugging.
468                  */
469                 page = ERR_PTR(err);
470                 if (err == -EEXIST) {
471                         /*
472                          * XXX in case of a lookup for CPT_TRANSIENT page,
473                          * nothing protects a CPT_CACHEABLE page from being
474                          * concurrently moved into CPS_FREEING state.
475                          */
476                         page = cl_page_lookup(hdr, idx);
477                         PASSERT(env, page, page != NULL);
478                         if (page->cp_type == CPT_TRANSIENT &&
479                             type == CPT_CACHEABLE) {
480                                 /* XXX: We should make sure that inode sem
481                                  * keeps being held in the lifetime of
482                                  * transient pages, so it is impossible to
483                                  * have conflicting transient pages.
484                                  */
485                                 cfs_spin_unlock(&hdr->coh_page_guard);
486                                 cl_page_put(env, page);
487                                 cfs_spin_lock(&hdr->coh_page_guard);
488                                 page = ERR_PTR(-EBUSY);
489                         }
490                 }
491         } else {
492                 if (parent) {
493                         LASSERT(page->cp_parent == NULL);
494                         page->cp_parent = parent;
495                         parent->cp_child = page;
496                 }
497                 hdr->coh_pages++;
498         }
499         cfs_spin_unlock(&hdr->coh_page_guard);
500
501         if (unlikely(ghost != NULL)) {
502                 cfs_atomic_dec(&site->cs_pages.cs_busy);
503                 cl_page_delete0(env, ghost, 0);
504                 cl_page_free(env, ghost);
505         }
506         RETURN(page);
507 }
508
509 struct cl_page *cl_page_find(const struct lu_env *env, struct cl_object *o,
510                              pgoff_t idx, struct page *vmpage,
511                              enum cl_page_type type)
512 {
513         return cl_page_find0(env, o, idx, vmpage, type, NULL);
514 }
515 EXPORT_SYMBOL(cl_page_find);
516
517
518 struct cl_page *cl_page_find_sub(const struct lu_env *env, struct cl_object *o,
519                                  pgoff_t idx, struct page *vmpage,
520                                  struct cl_page *parent)
521 {
522         return cl_page_find0(env, o, idx, vmpage, parent->cp_type, parent);
523 }
524 EXPORT_SYMBOL(cl_page_find_sub);
525
526 static inline int cl_page_invariant(const struct cl_page *pg)
527 {
528         struct cl_object_header *header;
529         struct cl_page          *parent;
530         struct cl_page          *child;
531         struct cl_io            *owner;
532
533         /*
534          * Page invariant is protected by a VM lock.
535          */
536         LINVRNT(cl_page_is_vmlocked(NULL, pg));
537
538         header = cl_object_header(pg->cp_obj);
539         parent = pg->cp_parent;
540         child  = pg->cp_child;
541         owner  = pg->cp_owner;
542
543         return cfs_atomic_read(&pg->cp_ref) > 0 &&
544                 ergo(parent != NULL, parent->cp_child == pg) &&
545                 ergo(child != NULL, child->cp_parent == pg) &&
546                 ergo(child != NULL, pg->cp_obj != child->cp_obj) &&
547                 ergo(parent != NULL, pg->cp_obj != parent->cp_obj) &&
548                 ergo(owner != NULL && parent != NULL,
549                      parent->cp_owner == pg->cp_owner->ci_parent) &&
550                 ergo(owner != NULL && child != NULL,
551                      child->cp_owner->ci_parent == owner) &&
552                 /*
553                  * Either page is early in initialization (has neither child
554                  * nor parent yet), or it is in the object radix tree.
555                  */
556                 ergo(pg->cp_state < CPS_FREEING,
557                      (void *)radix_tree_lookup(&header->coh_tree,
558                                                pg->cp_index) == pg ||
559                      (child == NULL && parent == NULL));
560 }
561
562 static void cl_page_state_set0(const struct lu_env *env,
563                                struct cl_page *page, enum cl_page_state state)
564 {
565         enum cl_page_state old;
566 #ifdef LUSTRE_PAGESTATE_TRACKING
567         struct cl_site *site = cl_object_site(page->cp_obj);
568 #endif
569
570         /*
571          * Matrix of allowed state transitions [old][new], for sanity
572          * checking.
573          */
574         static const int allowed_transitions[CPS_NR][CPS_NR] = {
575                 [CPS_CACHED] = {
576                         [CPS_CACHED]  = 0,
577                         [CPS_OWNED]   = 1, /* io finds existing cached page */
578                         [CPS_PAGEIN]  = 0,
579                         [CPS_PAGEOUT] = 1, /* write-out from the cache */
580                         [CPS_FREEING] = 1, /* eviction on the memory pressure */
581                 },
582                 [CPS_OWNED] = {
583                         [CPS_CACHED]  = 1, /* release to the cache */
584                         [CPS_OWNED]   = 0,
585                         [CPS_PAGEIN]  = 1, /* start read immediately */
586                         [CPS_PAGEOUT] = 1, /* start write immediately */
587                         [CPS_FREEING] = 1, /* lock invalidation or truncate */
588                 },
589                 [CPS_PAGEIN] = {
590                         [CPS_CACHED]  = 1, /* io completion */
591                         [CPS_OWNED]   = 0,
592                         [CPS_PAGEIN]  = 0,
593                         [CPS_PAGEOUT] = 0,
594                         [CPS_FREEING] = 0,
595                 },
596                 [CPS_PAGEOUT] = {
597                         [CPS_CACHED]  = 1, /* io completion */
598                         [CPS_OWNED]   = 0,
599                         [CPS_PAGEIN]  = 0,
600                         [CPS_PAGEOUT] = 0,
601                         [CPS_FREEING] = 0,
602                 },
603                 [CPS_FREEING] = {
604                         [CPS_CACHED]  = 0,
605                         [CPS_OWNED]   = 0,
606                         [CPS_PAGEIN]  = 0,
607                         [CPS_PAGEOUT] = 0,
608                         [CPS_FREEING] = 0,
609                 }
610         };
611
612         ENTRY;
613         old = page->cp_state;
614         PASSERT(env, page, allowed_transitions[old][state]);
615         CL_PAGE_HEADER(D_TRACE, env, page, "%d -> %d\n", old, state);
616         for (; page != NULL; page = page->cp_child) {
617                 PASSERT(env, page, page->cp_state == old);
618                 PASSERT(env, page,
619                         equi(state == CPS_OWNED, page->cp_owner != NULL));
620
621 #ifdef LUSTRE_PAGESTATE_TRACKING
622                 cfs_atomic_dec(&site->cs_pages_state[page->cp_state]);
623                 cfs_atomic_inc(&site->cs_pages_state[state]);
624 #endif
625                 cl_page_state_set_trust(page, state);
626         }
627         EXIT;
628 }
629
630 static void cl_page_state_set(const struct lu_env *env,
631                               struct cl_page *page, enum cl_page_state state)
632 {
633         PINVRNT(env, page, cl_page_invariant(page));
634         cl_page_state_set0(env, page, state);
635 }
636
637 /**
638  * Acquires an additional reference to a page.
639  *
640  * This can be called only by caller already possessing a reference to \a
641  * page.
642  *
643  * \see cl_object_get(), cl_lock_get().
644  */
645 void cl_page_get(struct cl_page *page)
646 {
647         ENTRY;
648         LASSERT(page->cp_state != CPS_FREEING);
649         cl_page_get_trust(page);
650         EXIT;
651 }
652 EXPORT_SYMBOL(cl_page_get);
653
654 /**
655  * Releases a reference to a page.
656  *
657  * When last reference is released, page is returned to the cache, unless it
658  * is in cl_page_state::CPS_FREEING state, in which case it is immediately
659  * destroyed.
660  *
661  * \see cl_object_put(), cl_lock_put().
662  */
663 void cl_page_put(const struct lu_env *env, struct cl_page *page)
664 {
665         struct cl_object_header *hdr;
666         struct cl_site *site = cl_object_site(page->cp_obj);
667
668         PASSERT(env, page, cfs_atomic_read(&page->cp_ref) > !!page->cp_parent);
669
670         ENTRY;
671         CL_PAGE_HEADER(D_TRACE, env, page, "%d\n",
672                        cfs_atomic_read(&page->cp_ref));
673
674         hdr = cl_object_header(cl_object_top(page->cp_obj));
675         if (cfs_atomic_dec_and_lock(&page->cp_ref, &hdr->coh_page_guard)) {
676                 cfs_atomic_dec(&site->cs_pages.cs_busy);
677                 /* We're going to access the page w/o a reference, but it's
678                  * ok because we have grabbed the lock coh_page_guard, which
679                  * means nobody is able to free this page behind us.
680                  */
681                 if (page->cp_state == CPS_FREEING) {
682                         /* We drop the page reference and check the page state
683                          * inside the coh_page_guard. So that if it gets here,
684                          * it is the REALLY last reference to this page.
685                          */
686                         cfs_spin_unlock(&hdr->coh_page_guard);
687
688                         LASSERT(cfs_atomic_read(&page->cp_ref) == 0);
689                         PASSERT(env, page, page->cp_owner == NULL);
690                         PASSERT(env, page, cfs_list_empty(&page->cp_batch));
691                         /*
692                          * Page is no longer reachable by other threads. Tear
693                          * it down.
694                          */
695                         cl_page_free(env, page);
696
697                         EXIT;
698                         return;
699                 }
700                 cfs_spin_unlock(&hdr->coh_page_guard);
701         }
702
703         EXIT;
704 }
705 EXPORT_SYMBOL(cl_page_put);
706
707 /**
708  * Returns a VM page associated with a given cl_page.
709  */
710 cfs_page_t *cl_page_vmpage(const struct lu_env *env, struct cl_page *page)
711 {
712         const struct cl_page_slice *slice;
713
714         /*
715          * Find uppermost layer with ->cpo_vmpage() method, and return its
716          * result.
717          */
718         page = cl_page_top(page);
719         do {
720                 cfs_list_for_each_entry(slice, &page->cp_layers, cpl_linkage) {
721                         if (slice->cpl_ops->cpo_vmpage != NULL)
722                                 RETURN(slice->cpl_ops->cpo_vmpage(env, slice));
723                 }
724                 page = page->cp_child;
725         } while (page != NULL);
726         LBUG(); /* ->cpo_vmpage() has to be defined somewhere in the stack */
727 }
728 EXPORT_SYMBOL(cl_page_vmpage);
729
730 /**
731  * Returns a cl_page associated with a VM page, and given cl_object.
732  */
733 struct cl_page *cl_vmpage_page(cfs_page_t *vmpage, struct cl_object *obj)
734 {
735         struct cl_page *page;
736         struct cl_object_header *hdr;
737
738         ENTRY;
739         KLASSERT(PageLocked(vmpage));
740
741         /*
742          * NOTE: absence of races and liveness of data are guaranteed by page
743          *       lock on a "vmpage". That works because object destruction has
744          *       bottom-to-top pass.
745          */
746
747         /*
748          * This loop assumes that ->private points to the top-most page. This
749          * can be rectified easily.
750          */
751         hdr = cl_object_header(cl_object_top(obj));
752         cfs_spin_lock(&hdr->coh_page_guard);
753         for (page = (void *)vmpage->private;
754              page != NULL; page = page->cp_child) {
755                 if (cl_object_same(page->cp_obj, obj)) {
756                         cl_page_get_trust(page);
757                         break;
758                 }
759         }
760         cfs_spin_unlock(&hdr->coh_page_guard);
761         LASSERT(ergo(page, page->cp_type == CPT_CACHEABLE));
762         RETURN(page);
763 }
764 EXPORT_SYMBOL(cl_vmpage_page);
765
766 /**
767  * Returns the top-page for a given page.
768  *
769  * \see cl_object_top(), cl_io_top()
770  */
771 struct cl_page *cl_page_top(struct cl_page *page)
772 {
773         return cl_page_top_trusted(page);
774 }
775 EXPORT_SYMBOL(cl_page_top);
776
777 const struct cl_page_slice *cl_page_at(const struct cl_page *page,
778                                        const struct lu_device_type *dtype)
779 {
780         return cl_page_at_trusted(page, dtype);
781 }
782 EXPORT_SYMBOL(cl_page_at);
783
784 #define CL_PAGE_OP(opname) offsetof(struct cl_page_operations, opname)
785
786 #define CL_PAGE_INVOKE(_env, _page, _op, _proto, ...)                   \
787 ({                                                                      \
788         const struct lu_env        *__env  = (_env);                    \
789         struct cl_page             *__page = (_page);                   \
790         const struct cl_page_slice *__scan;                             \
791         int                         __result;                           \
792         ptrdiff_t                   __op   = (_op);                     \
793         int                       (*__method)_proto;                    \
794                                                                         \
795         __result = 0;                                                   \
796         __page = cl_page_top(__page);                                   \
797         do {                                                            \
798                 cfs_list_for_each_entry(__scan, &__page->cp_layers,     \
799                                         cpl_linkage) {                  \
800                         __method = *(void **)((char *)__scan->cpl_ops + \
801                                               __op);                    \
802                         if (__method != NULL) {                         \
803                                 __result = (*__method)(__env, __scan,   \
804                                                        ## __VA_ARGS__); \
805                                 if (__result != 0)                      \
806                                         break;                          \
807                         }                                               \
808                 }                                                       \
809                 __page = __page->cp_child;                              \
810         } while (__page != NULL && __result == 0);                      \
811         if (__result > 0)                                               \
812                 __result = 0;                                           \
813         __result;                                                       \
814 })
815
816 #define CL_PAGE_INVOID(_env, _page, _op, _proto, ...)                   \
817 do {                                                                    \
818         const struct lu_env        *__env  = (_env);                    \
819         struct cl_page             *__page = (_page);                   \
820         const struct cl_page_slice *__scan;                             \
821         ptrdiff_t                   __op   = (_op);                     \
822         void                      (*__method)_proto;                    \
823                                                                         \
824         __page = cl_page_top(__page);                                   \
825         do {                                                            \
826                 cfs_list_for_each_entry(__scan, &__page->cp_layers,     \
827                                         cpl_linkage) {                  \
828                         __method = *(void **)((char *)__scan->cpl_ops + \
829                                               __op);                    \
830                         if (__method != NULL)                           \
831                                 (*__method)(__env, __scan,              \
832                                             ## __VA_ARGS__);            \
833                 }                                                       \
834                 __page = __page->cp_child;                              \
835         } while (__page != NULL);                                       \
836 } while (0)
837
838 #define CL_PAGE_INVOID_REVERSE(_env, _page, _op, _proto, ...)               \
839 do {                                                                        \
840         const struct lu_env        *__env  = (_env);                        \
841         struct cl_page             *__page = (_page);                       \
842         const struct cl_page_slice *__scan;                                 \
843         ptrdiff_t                   __op   = (_op);                         \
844         void                      (*__method)_proto;                        \
845                                                                             \
846         /* get to the bottom page. */                                       \
847         while (__page->cp_child != NULL)                                    \
848                 __page = __page->cp_child;                                  \
849         do {                                                                \
850                 cfs_list_for_each_entry_reverse(__scan, &__page->cp_layers, \
851                                                 cpl_linkage) {              \
852                         __method = *(void **)((char *)__scan->cpl_ops +     \
853                                               __op);                        \
854                         if (__method != NULL)                               \
855                                 (*__method)(__env, __scan,                  \
856                                             ## __VA_ARGS__);                \
857                 }                                                           \
858                 __page = __page->cp_parent;                                 \
859         } while (__page != NULL);                                           \
860 } while (0)
861
862 static int cl_page_invoke(const struct lu_env *env,
863                           struct cl_io *io, struct cl_page *page, ptrdiff_t op)
864
865 {
866         PINVRNT(env, page, cl_object_same(page->cp_obj, io->ci_obj));
867         ENTRY;
868         RETURN(CL_PAGE_INVOKE(env, page, op,
869                               (const struct lu_env *,
870                                const struct cl_page_slice *, struct cl_io *),
871                               io));
872 }
873
874 static void cl_page_invoid(const struct lu_env *env,
875                            struct cl_io *io, struct cl_page *page, ptrdiff_t op)
876
877 {
878         PINVRNT(env, page, cl_object_same(page->cp_obj, io->ci_obj));
879         ENTRY;
880         CL_PAGE_INVOID(env, page, op,
881                        (const struct lu_env *,
882                         const struct cl_page_slice *, struct cl_io *), io);
883         EXIT;
884 }
885
886 static void cl_page_owner_clear(struct cl_page *page)
887 {
888         ENTRY;
889         for (page = cl_page_top(page); page != NULL; page = page->cp_child) {
890                 if (page->cp_owner != NULL) {
891                         LASSERT(page->cp_owner->ci_owned_nr > 0);
892                         page->cp_owner->ci_owned_nr--;
893                         page->cp_owner = NULL;
894                         page->cp_task = NULL;
895                 }
896         }
897         EXIT;
898 }
899
900 static void cl_page_owner_set(struct cl_page *page)
901 {
902         ENTRY;
903         for (page = cl_page_top(page); page != NULL; page = page->cp_child) {
904                 LASSERT(page->cp_owner != NULL);
905                 page->cp_owner->ci_owned_nr++;
906         }
907         EXIT;
908 }
909
910 void cl_page_disown0(const struct lu_env *env,
911                      struct cl_io *io, struct cl_page *pg)
912 {
913         enum cl_page_state state;
914
915         ENTRY;
916         state = pg->cp_state;
917         PINVRNT(env, pg, state == CPS_OWNED || state == CPS_FREEING);
918         PINVRNT(env, pg, cl_page_invariant(pg));
919         cl_page_owner_clear(pg);
920
921         if (state == CPS_OWNED)
922                 cl_page_state_set(env, pg, CPS_CACHED);
923         /*
924          * Completion call-backs are executed in the bottom-up order, so that
925          * uppermost layer (llite), responsible for VFS/VM interaction runs
926          * last and can release locks safely.
927          */
928         CL_PAGE_INVOID_REVERSE(env, pg, CL_PAGE_OP(cpo_disown),
929                                (const struct lu_env *,
930                                 const struct cl_page_slice *, struct cl_io *),
931                                io);
932         EXIT;
933 }
934
935 /**
936  * returns true, iff page is owned by the given io.
937  */
938 int cl_page_is_owned(const struct cl_page *pg, const struct cl_io *io)
939 {
940         LINVRNT(cl_object_same(pg->cp_obj, io->ci_obj));
941         ENTRY;
942         RETURN(pg->cp_state == CPS_OWNED && pg->cp_owner == io);
943 }
944 EXPORT_SYMBOL(cl_page_is_owned);
945
946 /**
947  * Try to own a page by IO.
948  *
949  * Waits until page is in cl_page_state::CPS_CACHED state, and then switch it
950  * into cl_page_state::CPS_OWNED state.
951  *
952  * \pre  !cl_page_is_owned(pg, io)
953  * \post result == 0 iff cl_page_is_owned(pg, io)
954  *
955  * \retval 0   success
956  *
957  * \retval -ve failure, e.g., page was destroyed (and landed in
958  *             cl_page_state::CPS_FREEING instead of cl_page_state::CPS_CACHED).
959  *             or, page was owned by another thread, or in IO.
960  *
961  * \see cl_page_disown()
962  * \see cl_page_operations::cpo_own()
963  * \see cl_page_own_try()
964  * \see cl_page_own
965  */
966 static int cl_page_own0(const struct lu_env *env, struct cl_io *io,
967                         struct cl_page *pg, int nonblock)
968 {
969         int result;
970
971         PINVRNT(env, pg, !cl_page_is_owned(pg, io));
972
973         ENTRY;
974         pg = cl_page_top(pg);
975         io = cl_io_top(io);
976
977         if (pg->cp_state == CPS_FREEING) {
978                 result = -EAGAIN;
979         } else {
980                 result = CL_PAGE_INVOKE(env, pg, CL_PAGE_OP(cpo_own),
981                                         (const struct lu_env *,
982                                          const struct cl_page_slice *,
983                                          struct cl_io *, int),
984                                         io, nonblock);
985                 if (result == 0) {
986                         PASSERT(env, pg, pg->cp_owner == NULL);
987                         PASSERT(env, pg, pg->cp_req == NULL);
988                         pg->cp_owner = io;
989                         pg->cp_task  = current;
990                         cl_page_owner_set(pg);
991                         if (pg->cp_state != CPS_FREEING) {
992                                 cl_page_state_set(env, pg, CPS_OWNED);
993                         } else {
994                                 cl_page_disown0(env, io, pg);
995                                 result = -EAGAIN;
996                         }
997                 }
998         }
999         PINVRNT(env, pg, ergo(result == 0, cl_page_invariant(pg)));
1000         RETURN(result);
1001 }
1002
1003 /**
1004  * Own a page, might be blocked.
1005  *
1006  * \see cl_page_own0()
1007  */
1008 int cl_page_own(const struct lu_env *env, struct cl_io *io, struct cl_page *pg)
1009 {
1010         return cl_page_own0(env, io, pg, 0);
1011 }
1012 EXPORT_SYMBOL(cl_page_own);
1013
1014 /**
1015  * Nonblock version of cl_page_own().
1016  *
1017  * \see cl_page_own0()
1018  */
1019 int cl_page_own_try(const struct lu_env *env, struct cl_io *io,
1020                     struct cl_page *pg)
1021 {
1022         return cl_page_own0(env, io, pg, 1);
1023 }
1024 EXPORT_SYMBOL(cl_page_own_try);
1025
1026
1027 /**
1028  * Assume page ownership.
1029  *
1030  * Called when page is already locked by the hosting VM.
1031  *
1032  * \pre !cl_page_is_owned(pg, io)
1033  * \post cl_page_is_owned(pg, io)
1034  *
1035  * \see cl_page_operations::cpo_assume()
1036  */
1037 void cl_page_assume(const struct lu_env *env,
1038                     struct cl_io *io, struct cl_page *pg)
1039 {
1040         PASSERT(env, pg, pg->cp_state < CPS_OWNED);
1041         PASSERT(env, pg, pg->cp_owner == NULL);
1042         PINVRNT(env, pg, cl_object_same(pg->cp_obj, io->ci_obj));
1043         PINVRNT(env, pg, cl_page_invariant(pg));
1044
1045         ENTRY;
1046         pg = cl_page_top(pg);
1047         io = cl_io_top(io);
1048
1049         cl_page_invoid(env, io, pg, CL_PAGE_OP(cpo_assume));
1050         pg->cp_owner = io;
1051         pg->cp_task = current;
1052         cl_page_owner_set(pg);
1053         cl_page_state_set(env, pg, CPS_OWNED);
1054         EXIT;
1055 }
1056 EXPORT_SYMBOL(cl_page_assume);
1057
1058 /**
1059  * Releases page ownership without unlocking the page.
1060  *
1061  * Moves page into cl_page_state::CPS_CACHED without releasing a lock on the
1062  * underlying VM page (as VM is supposed to do this itself).
1063  *
1064  * \pre   cl_page_is_owned(pg, io)
1065  * \post !cl_page_is_owned(pg, io)
1066  *
1067  * \see cl_page_assume()
1068  */
1069 void cl_page_unassume(const struct lu_env *env,
1070                       struct cl_io *io, struct cl_page *pg)
1071 {
1072         PINVRNT(env, pg, cl_page_is_owned(pg, io));
1073         PINVRNT(env, pg, cl_page_invariant(pg));
1074
1075         ENTRY;
1076         pg = cl_page_top(pg);
1077         io = cl_io_top(io);
1078         cl_page_owner_clear(pg);
1079         cl_page_state_set(env, pg, CPS_CACHED);
1080         CL_PAGE_INVOID_REVERSE(env, pg, CL_PAGE_OP(cpo_unassume),
1081                                (const struct lu_env *,
1082                                 const struct cl_page_slice *, struct cl_io *),
1083                                io);
1084         EXIT;
1085 }
1086 EXPORT_SYMBOL(cl_page_unassume);
1087
1088 /**
1089  * Releases page ownership.
1090  *
1091  * Moves page into cl_page_state::CPS_CACHED.
1092  *
1093  * \pre   cl_page_is_owned(pg, io)
1094  * \post !cl_page_is_owned(pg, io)
1095  *
1096  * \see cl_page_own()
1097  * \see cl_page_operations::cpo_disown()
1098  */
1099 void cl_page_disown(const struct lu_env *env,
1100                     struct cl_io *io, struct cl_page *pg)
1101 {
1102         PINVRNT(env, pg, cl_page_is_owned(pg, io));
1103
1104         ENTRY;
1105         pg = cl_page_top(pg);
1106         io = cl_io_top(io);
1107         cl_page_disown0(env, io, pg);
1108         EXIT;
1109 }
1110 EXPORT_SYMBOL(cl_page_disown);
1111
1112 /**
1113  * Called when page is to be removed from the object, e.g., as a result of
1114  * truncate.
1115  *
1116  * Calls cl_page_operations::cpo_discard() top-to-bottom.
1117  *
1118  * \pre cl_page_is_owned(pg, io)
1119  *
1120  * \see cl_page_operations::cpo_discard()
1121  */
1122 void cl_page_discard(const struct lu_env *env,
1123                      struct cl_io *io, struct cl_page *pg)
1124 {
1125         PINVRNT(env, pg, cl_page_is_owned(pg, io));
1126         PINVRNT(env, pg, cl_page_invariant(pg));
1127
1128         cl_page_invoid(env, io, pg, CL_PAGE_OP(cpo_discard));
1129 }
1130 EXPORT_SYMBOL(cl_page_discard);
1131
1132 /**
1133  * Version of cl_page_delete() that can be called for not fully constructed
1134  * pages, e.g,. in a error handling cl_page_find()->cl_page_delete0()
1135  * path. Doesn't check page invariant.
1136  */
1137 static void cl_page_delete0(const struct lu_env *env, struct cl_page *pg,
1138                             int radix)
1139 {
1140         struct cl_page *tmp = pg;
1141         ENTRY;
1142
1143         PASSERT(env, pg, pg == cl_page_top(pg));
1144         PASSERT(env, pg, pg->cp_state != CPS_FREEING);
1145
1146         /*
1147          * Severe all ways to obtain new pointers to @pg.
1148          */
1149         cl_page_owner_clear(pg);
1150
1151         /* 
1152          * unexport the page firstly before freeing it so that
1153          * the page content is considered to be invalid.
1154          * We have to do this because a CPS_FREEING cl_page may
1155          * be NOT under the protection of a cl_lock.
1156          * Afterwards, if this page is found by other threads, then this
1157          * page will be forced to reread.
1158          */
1159         cl_page_export(env, pg, 0);
1160         cl_page_state_set0(env, pg, CPS_FREEING);
1161
1162         if (!radix)
1163                 /*
1164                  * !radix means that @pg is not yet in the radix tree, skip
1165                  * removing it.
1166                  */
1167                 tmp = pg->cp_child;
1168         for (; tmp != NULL; tmp = tmp->cp_child) {
1169                 void                    *value;
1170                 struct cl_object_header *hdr;
1171
1172                 hdr = cl_object_header(tmp->cp_obj);
1173                 cfs_spin_lock(&hdr->coh_page_guard);
1174                 value = radix_tree_delete(&hdr->coh_tree, tmp->cp_index);
1175                 PASSERT(env, tmp, value == tmp);
1176                 PASSERT(env, tmp, hdr->coh_pages > 0);
1177                 hdr->coh_pages--;
1178                 cfs_spin_unlock(&hdr->coh_page_guard);
1179         }
1180
1181         CL_PAGE_INVOID(env, pg, CL_PAGE_OP(cpo_delete),
1182                        (const struct lu_env *, const struct cl_page_slice *));
1183         EXIT;
1184 }
1185
1186 /**
1187  * Called when a decision is made to throw page out of memory.
1188  *
1189  * Notifies all layers about page destruction by calling
1190  * cl_page_operations::cpo_delete() method top-to-bottom.
1191  *
1192  * Moves page into cl_page_state::CPS_FREEING state (this is the only place
1193  * where transition to this state happens).
1194  *
1195  * Eliminates all venues through which new references to the page can be
1196  * obtained:
1197  *
1198  *     - removes page from the radix trees,
1199  *
1200  *     - breaks linkage from VM page to cl_page.
1201  *
1202  * Once page reaches cl_page_state::CPS_FREEING, all remaining references will
1203  * drain after some time, at which point page will be recycled.
1204  *
1205  * \pre  pg == cl_page_top(pg)
1206  * \pre  VM page is locked
1207  * \post pg->cp_state == CPS_FREEING
1208  *
1209  * \see cl_page_operations::cpo_delete()
1210  */
1211 void cl_page_delete(const struct lu_env *env, struct cl_page *pg)
1212 {
1213         PINVRNT(env, pg, cl_page_invariant(pg));
1214         ENTRY;
1215         cl_page_delete0(env, pg, 1);
1216         EXIT;
1217 }
1218 EXPORT_SYMBOL(cl_page_delete);
1219
1220 /**
1221  * Unmaps page from user virtual memory.
1222  *
1223  * Calls cl_page_operations::cpo_unmap() through all layers top-to-bottom. The
1224  * layer responsible for VM interaction has to unmap page from user space
1225  * virtual memory.
1226  *
1227  * \see cl_page_operations::cpo_unmap()
1228  */
1229 int cl_page_unmap(const struct lu_env *env,
1230                   struct cl_io *io, struct cl_page *pg)
1231 {
1232         PINVRNT(env, pg, cl_page_is_owned(pg, io));
1233         PINVRNT(env, pg, cl_page_invariant(pg));
1234
1235         return cl_page_invoke(env, io, pg, CL_PAGE_OP(cpo_unmap));
1236 }
1237 EXPORT_SYMBOL(cl_page_unmap);
1238
1239 /**
1240  * Marks page up-to-date.
1241  *
1242  * Call cl_page_operations::cpo_export() through all layers top-to-bottom. The
1243  * layer responsible for VM interaction has to mark/clear page as up-to-date
1244  * by the \a uptodate argument.
1245  *
1246  * \see cl_page_operations::cpo_export()
1247  */
1248 void cl_page_export(const struct lu_env *env, struct cl_page *pg, int uptodate)
1249 {
1250         PINVRNT(env, pg, cl_page_invariant(pg));
1251         CL_PAGE_INVOID(env, pg, CL_PAGE_OP(cpo_export),
1252                        (const struct lu_env *,
1253                         const struct cl_page_slice *, int), uptodate);
1254 }
1255 EXPORT_SYMBOL(cl_page_export);
1256
1257 /**
1258  * Returns true, iff \a pg is VM locked in a suitable sense by the calling
1259  * thread.
1260  */
1261 int cl_page_is_vmlocked(const struct lu_env *env, const struct cl_page *pg)
1262 {
1263         int result;
1264         const struct cl_page_slice *slice;
1265
1266         ENTRY;
1267         pg = cl_page_top_trusted((struct cl_page *)pg);
1268         slice = container_of(pg->cp_layers.next,
1269                              const struct cl_page_slice, cpl_linkage);
1270         PASSERT(env, pg, slice->cpl_ops->cpo_is_vmlocked != NULL);
1271         /*
1272          * Call ->cpo_is_vmlocked() directly instead of going through
1273          * CL_PAGE_INVOKE(), because cl_page_is_vmlocked() is used by
1274          * cl_page_invariant().
1275          */
1276         result = slice->cpl_ops->cpo_is_vmlocked(env, slice);
1277         PASSERT(env, pg, result == -EBUSY || result == -ENODATA);
1278         RETURN(result == -EBUSY);
1279 }
1280 EXPORT_SYMBOL(cl_page_is_vmlocked);
1281
1282 static enum cl_page_state cl_req_type_state(enum cl_req_type crt)
1283 {
1284         ENTRY;
1285         RETURN(crt == CRT_WRITE ? CPS_PAGEOUT : CPS_PAGEIN);
1286 }
1287
1288 static void cl_page_io_start(const struct lu_env *env,
1289                              struct cl_page *pg, enum cl_req_type crt)
1290 {
1291         /*
1292          * Page is queued for IO, change its state.
1293          */
1294         ENTRY;
1295         cl_page_owner_clear(pg);
1296         cl_page_state_set(env, pg, cl_req_type_state(crt));
1297         EXIT;
1298 }
1299
1300 /**
1301  * Prepares page for immediate transfer. cl_page_operations::cpo_prep() is
1302  * called top-to-bottom. Every layer either agrees to submit this page (by
1303  * returning 0), or requests to omit this page (by returning -EALREADY). Layer
1304  * handling interactions with the VM also has to inform VM that page is under
1305  * transfer now.
1306  */
1307 int cl_page_prep(const struct lu_env *env, struct cl_io *io,
1308                  struct cl_page *pg, enum cl_req_type crt)
1309 {
1310         int result;
1311
1312         PINVRNT(env, pg, cl_page_is_owned(pg, io));
1313         PINVRNT(env, pg, cl_page_invariant(pg));
1314         PINVRNT(env, pg, crt < CRT_NR);
1315
1316         /*
1317          * XXX this has to be called bottom-to-top, so that llite can set up
1318          * PG_writeback without risking other layers deciding to skip this
1319          * page.
1320          */
1321         result = cl_page_invoke(env, io, pg, CL_PAGE_OP(io[crt].cpo_prep));
1322         if (result == 0)
1323                 cl_page_io_start(env, pg, crt);
1324
1325         KLASSERT(ergo(crt == CRT_WRITE && pg->cp_type == CPT_CACHEABLE,
1326                       equi(result == 0,
1327                            PageWriteback(cl_page_vmpage(env, pg)))));
1328         CL_PAGE_HEADER(D_TRACE, env, pg, "%d %d\n", crt, result);
1329         return result;
1330 }
1331 EXPORT_SYMBOL(cl_page_prep);
1332
1333 /**
1334  * Notify layers about transfer completion.
1335  *
1336  * Invoked by transfer sub-system (which is a part of osc) to notify layers
1337  * that a transfer, of which this page is a part of has completed.
1338  *
1339  * Completion call-backs are executed in the bottom-up order, so that
1340  * uppermost layer (llite), responsible for the VFS/VM interaction runs last
1341  * and can release locks safely.
1342  *
1343  * \pre  pg->cp_state == CPS_PAGEIN || pg->cp_state == CPS_PAGEOUT
1344  * \post pg->cp_state == CPS_CACHED
1345  *
1346  * \see cl_page_operations::cpo_completion()
1347  */
1348 void cl_page_completion(const struct lu_env *env,
1349                         struct cl_page *pg, enum cl_req_type crt, int ioret)
1350 {
1351         struct cl_sync_io *anchor = pg->cp_sync_io;
1352
1353         PASSERT(env, pg, crt < CRT_NR);
1354         /* cl_page::cp_req already cleared by the caller (osc_completion()) */
1355         PASSERT(env, pg, pg->cp_req == NULL);
1356         PASSERT(env, pg, pg->cp_state == cl_req_type_state(crt));
1357         PINVRNT(env, pg, cl_page_invariant(pg));
1358
1359         ENTRY;
1360         CL_PAGE_HEADER(D_TRACE, env, pg, "%d %d\n", crt, ioret);
1361         if (crt == CRT_READ && ioret == 0) {
1362                 PASSERT(env, pg, !(pg->cp_flags & CPF_READ_COMPLETED));
1363                 pg->cp_flags |= CPF_READ_COMPLETED;
1364         }
1365
1366         cl_page_state_set(env, pg, CPS_CACHED);
1367         CL_PAGE_INVOID_REVERSE(env, pg, CL_PAGE_OP(io[crt].cpo_completion),
1368                                (const struct lu_env *,
1369                                 const struct cl_page_slice *, int), ioret);
1370         if (anchor) {
1371                 LASSERT(pg->cp_sync_io == anchor);
1372                 pg->cp_sync_io = NULL;
1373                 cl_sync_io_note(anchor, ioret);
1374         }
1375
1376         /* Don't assert the page writeback bit here because the lustre file
1377          * may be as a backend of swap space. in this case, the page writeback
1378          * is set by VM, and obvious we shouldn't clear it at all. Fortunately
1379          * this type of pages are all TRANSIENT pages. */
1380         KLASSERT(ergo(pg->cp_type == CPT_CACHEABLE,
1381                       !PageWriteback(cl_page_vmpage(env, pg))));
1382         EXIT;
1383 }
1384 EXPORT_SYMBOL(cl_page_completion);
1385
1386 /**
1387  * Notify layers that transfer formation engine decided to yank this page from
1388  * the cache and to make it a part of a transfer.
1389  *
1390  * \pre  pg->cp_state == CPS_CACHED
1391  * \post pg->cp_state == CPS_PAGEIN || pg->cp_state == CPS_PAGEOUT
1392  *
1393  * \see cl_page_operations::cpo_make_ready()
1394  */
1395 int cl_page_make_ready(const struct lu_env *env, struct cl_page *pg,
1396                        enum cl_req_type crt)
1397 {
1398         int result;
1399
1400         PINVRNT(env, pg, crt < CRT_NR);
1401
1402         ENTRY;
1403         result = CL_PAGE_INVOKE(env, pg, CL_PAGE_OP(io[crt].cpo_make_ready),
1404                                 (const struct lu_env *,
1405                                  const struct cl_page_slice *));
1406         if (result == 0) {
1407                 PASSERT(env, pg, pg->cp_state == CPS_CACHED);
1408                 cl_page_io_start(env, pg, crt);
1409         }
1410         CL_PAGE_HEADER(D_TRACE, env, pg, "%d %d\n", crt, result);
1411         RETURN(result);
1412 }
1413 EXPORT_SYMBOL(cl_page_make_ready);
1414
1415 /**
1416  * Notify layers that high level io decided to place this page into a cache
1417  * for future transfer.
1418  *
1419  * The layer implementing transfer engine (osc) has to register this page in
1420  * its queues.
1421  *
1422  * \pre  cl_page_is_owned(pg, io)
1423  * \post ergo(result == 0,
1424  *            pg->cp_state == CPS_PAGEIN || pg->cp_state == CPS_PAGEOUT)
1425  *
1426  * \see cl_page_operations::cpo_cache_add()
1427  */
1428 int cl_page_cache_add(const struct lu_env *env, struct cl_io *io,
1429                       struct cl_page *pg, enum cl_req_type crt)
1430 {
1431         int result;
1432
1433         PINVRNT(env, pg, crt < CRT_NR);
1434         PINVRNT(env, pg, cl_page_is_owned(pg, io));
1435         PINVRNT(env, pg, cl_page_invariant(pg));
1436
1437         ENTRY;
1438         result = cl_page_invoke(env, io, pg, CL_PAGE_OP(io[crt].cpo_cache_add));
1439         if (result == 0) {
1440                 cl_page_owner_clear(pg);
1441                 cl_page_state_set(env, pg, CPS_CACHED);
1442         }
1443         CL_PAGE_HEADER(D_TRACE, env, pg, "%d %d\n", crt, result);
1444         RETURN(result);
1445 }
1446 EXPORT_SYMBOL(cl_page_cache_add);
1447
1448 /**
1449  * Checks whether page is protected by any extent lock is at least required
1450  * mode.
1451  *
1452  * \return the same as in cl_page_operations::cpo_is_under_lock() method.
1453  * \see cl_page_operations::cpo_is_under_lock()
1454  */
1455 int cl_page_is_under_lock(const struct lu_env *env, struct cl_io *io,
1456                           struct cl_page *page)
1457 {
1458         int rc;
1459
1460         PINVRNT(env, page, cl_page_invariant(page));
1461
1462         ENTRY;
1463         rc = CL_PAGE_INVOKE(env, page, CL_PAGE_OP(cpo_is_under_lock),
1464                             (const struct lu_env *,
1465                              const struct cl_page_slice *, struct cl_io *),
1466                             io);
1467         PASSERT(env, page, rc != 0);
1468         RETURN(rc);
1469 }
1470 EXPORT_SYMBOL(cl_page_is_under_lock);
1471
1472 /**
1473  * Purges all cached pages belonging to the object \a obj.
1474  */
1475 int cl_pages_prune(const struct lu_env *env, struct cl_object *clobj)
1476 {
1477         struct cl_thread_info   *info;
1478         struct cl_object        *obj = cl_object_top(clobj);
1479         struct cl_io            *io;
1480         struct cl_page_list     *plist;
1481         int                      resched;
1482         int                      result;
1483
1484         ENTRY;
1485         info  = cl_env_info(env);
1486         plist = &info->clt_list;
1487         io    = &info->clt_io;
1488
1489         /*
1490          * initialize the io. This is ugly since we never do IO in this
1491          * function, we just make cl_page_list functions happy. -jay
1492          */
1493         io->ci_obj = obj;
1494         result = cl_io_init(env, io, CIT_MISC, obj);
1495         if (result != 0) {
1496                 cl_io_fini(env, io);
1497                 RETURN(io->ci_result);
1498         }
1499
1500         do {
1501                 cl_page_list_init(plist);
1502                 cl_page_gang_lookup(env, obj, io, 0, CL_PAGE_EOF, plist, 0,
1503                                     &resched);
1504                 /*
1505                  * Since we're purging the pages of an object, we don't care
1506                  * the possible outcomes of the following functions.
1507                  */
1508                 cl_page_list_unmap(env, io, plist);
1509                 cl_page_list_discard(env, io, plist);
1510                 cl_page_list_disown(env, io, plist);
1511                 cl_page_list_fini(env, plist);
1512
1513                 if (resched)
1514                         cfs_cond_resched();
1515         } while (resched);
1516
1517         cl_io_fini(env, io);
1518         RETURN(result);
1519 }
1520 EXPORT_SYMBOL(cl_pages_prune);
1521
1522 /**
1523  * Tells transfer engine that only part of a page is to be transmitted.
1524  *
1525  * \see cl_page_operations::cpo_clip()
1526  */
1527 void cl_page_clip(const struct lu_env *env, struct cl_page *pg,
1528                   int from, int to)
1529 {
1530         PINVRNT(env, pg, cl_page_invariant(pg));
1531
1532         CL_PAGE_HEADER(D_TRACE, env, pg, "%d %d\n", from, to);
1533         CL_PAGE_INVOID(env, pg, CL_PAGE_OP(cpo_clip),
1534                        (const struct lu_env *,
1535                         const struct cl_page_slice *,int, int),
1536                        from, to);
1537 }
1538 EXPORT_SYMBOL(cl_page_clip);
1539
1540 /**
1541  * Prints human readable representation of \a pg to the \a f.
1542  */
1543 void cl_page_header_print(const struct lu_env *env, void *cookie,
1544                           lu_printer_t printer, const struct cl_page *pg)
1545 {
1546         (*printer)(env, cookie,
1547                    "page@%p[%d %p:%lu ^%p_%p %d %d %d %p %p %#x]\n",
1548                    pg, cfs_atomic_read(&pg->cp_ref), pg->cp_obj,
1549                    pg->cp_index, pg->cp_parent, pg->cp_child,
1550                    pg->cp_state, pg->cp_error, pg->cp_type,
1551                    pg->cp_owner, pg->cp_req, pg->cp_flags);
1552 }
1553 EXPORT_SYMBOL(cl_page_header_print);
1554
1555 /**
1556  * Prints human readable representation of \a pg to the \a f.
1557  */
1558 void cl_page_print(const struct lu_env *env, void *cookie,
1559                    lu_printer_t printer, const struct cl_page *pg)
1560 {
1561         struct cl_page *scan;
1562
1563         for (scan = cl_page_top((struct cl_page *)pg);
1564              scan != NULL; scan = scan->cp_child)
1565                 cl_page_header_print(env, cookie, printer, scan);
1566         CL_PAGE_INVOKE(env, (struct cl_page *)pg, CL_PAGE_OP(cpo_print),
1567                        (const struct lu_env *env,
1568                         const struct cl_page_slice *slice,
1569                         void *cookie, lu_printer_t p), cookie, printer);
1570         (*printer)(env, cookie, "end page@%p\n", pg);
1571 }
1572 EXPORT_SYMBOL(cl_page_print);
1573
1574 /**
1575  * Cancel a page which is still in a transfer.
1576  */
1577 int cl_page_cancel(const struct lu_env *env, struct cl_page *page)
1578 {
1579         return CL_PAGE_INVOKE(env, page, CL_PAGE_OP(cpo_cancel),
1580                               (const struct lu_env *,
1581                                const struct cl_page_slice *));
1582 }
1583 EXPORT_SYMBOL(cl_page_cancel);
1584
1585 /**
1586  * Converts a byte offset within object \a obj into a page index.
1587  */
1588 loff_t cl_offset(const struct cl_object *obj, pgoff_t idx)
1589 {
1590         /*
1591          * XXX for now.
1592          */
1593         return (loff_t)idx << CFS_PAGE_SHIFT;
1594 }
1595 EXPORT_SYMBOL(cl_offset);
1596
1597 /**
1598  * Converts a page index into a byte offset within object \a obj.
1599  */
1600 pgoff_t cl_index(const struct cl_object *obj, loff_t offset)
1601 {
1602         /*
1603          * XXX for now.
1604          */
1605         return offset >> CFS_PAGE_SHIFT;
1606 }
1607 EXPORT_SYMBOL(cl_index);
1608
1609 int cl_page_size(const struct cl_object *obj)
1610 {
1611         return 1 << CFS_PAGE_SHIFT;
1612 }
1613 EXPORT_SYMBOL(cl_page_size);
1614
1615 /**
1616  * Adds page slice to the compound page.
1617  *
1618  * This is called by cl_object_operations::coo_page_init() methods to add a
1619  * per-layer state to the page. New state is added at the end of
1620  * cl_page::cp_layers list, that is, it is at the bottom of the stack.
1621  *
1622  * \see cl_lock_slice_add(), cl_req_slice_add(), cl_io_slice_add()
1623  */
1624 void cl_page_slice_add(struct cl_page *page, struct cl_page_slice *slice,
1625                        struct cl_object *obj,
1626                        const struct cl_page_operations *ops)
1627 {
1628         ENTRY;
1629         cfs_list_add_tail(&slice->cpl_linkage, &page->cp_layers);
1630         slice->cpl_obj  = obj;
1631         slice->cpl_ops  = ops;
1632         slice->cpl_page = page;
1633         EXIT;
1634 }
1635 EXPORT_SYMBOL(cl_page_slice_add);
1636
1637 int  cl_page_init(void)
1638 {
1639         return lu_kmem_init(cl_page_caches);
1640 }
1641
1642 void cl_page_fini(void)
1643 {
1644         lu_kmem_fini(cl_page_caches);
1645 }