Whamcloud - gitweb
e78d05a41a7acf27c467eb3dec47c2dd134197a6
[fs/lustre-release.git] / lustre / include / cl_object.h
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2011, 2012, Intel Corporation.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  */
36 #ifndef _LUSTRE_CL_OBJECT_H
37 #define _LUSTRE_CL_OBJECT_H
38
39 /** \defgroup clio clio
40  *
41  * Client objects implement io operations and cache pages.
42  *
43  * Examples: lov and osc are implementations of cl interface.
44  *
45  * Big Theory Statement.
46  *
47  * Layered objects.
48  *
49  * Client implementation is based on the following data-types:
50  *
51  *   - cl_object
52  *
53  *   - cl_page
54  *
55  *   - cl_lock     represents an extent lock on an object.
56  *
57  *   - cl_io       represents high-level i/o activity such as whole read/write
58  *                 system call, or write-out of pages from under the lock being
59  *                 canceled. cl_io has sub-ios that can be stopped and resumed
60  *                 independently, thus achieving high degree of transfer
61  *                 parallelism. Single cl_io can be advanced forward by
62  *                 the multiple threads (although in the most usual case of
63  *                 read/write system call it is associated with the single user
64  *                 thread, that issued the system call).
65  *
66  *   - cl_req      represents a collection of pages for a transfer. cl_req is
67  *                 constructed by req-forming engine that tries to saturate
68  *                 transport with large and continuous transfers.
69  *
70  * Terminology
71  *
72  *     - to avoid confusion high-level I/O operation like read or write system
73  *     call is referred to as "an io", whereas low-level I/O operation, like
74  *     RPC, is referred to as "a transfer"
75  *
76  *     - "generic code" means generic (not file system specific) code in the
77  *     hosting environment. "cl-code" means code (mostly in cl_*.c files) that
78  *     is not layer specific.
79  *
80  * Locking.
81  *
82  *  - i_mutex
83  *      - PG_locked
84  *          - cl_object_header::coh_page_guard
85  *          - cl_object_header::coh_lock_guard
86  *          - lu_site::ls_guard
87  *
88  * See the top comment in cl_object.c for the description of overall locking and
89  * reference-counting design.
90  *
91  * See comments below for the description of i/o, page, and dlm-locking
92  * design.
93  *
94  * @{
95  */
96
97 /*
98  * super-class definitions.
99  */
100 #include <lu_object.h>
101 #include <lvfs.h>
102 #ifdef __KERNEL__
103 #        include <linux/mutex.h>
104 #        include <linux/radix-tree.h>
105 #endif
106
107 struct inode;
108
109 struct cl_device;
110 struct cl_device_operations;
111
112 struct cl_object;
113 struct cl_object_page_operations;
114 struct cl_object_lock_operations;
115
116 struct cl_page;
117 struct cl_page_slice;
118 struct cl_lock;
119 struct cl_lock_slice;
120
121 struct cl_lock_operations;
122 struct cl_page_operations;
123
124 struct cl_io;
125 struct cl_io_slice;
126
127 struct cl_req;
128 struct cl_req_slice;
129
130 /**
131  * Operations for each data device in the client stack.
132  *
133  * \see vvp_cl_ops, lov_cl_ops, lovsub_cl_ops, osc_cl_ops
134  */
135 struct cl_device_operations {
136         /**
137          * Initialize cl_req. This method is called top-to-bottom on all
138          * devices in the stack to get them a chance to allocate layer-private
139          * data, and to attach them to the cl_req by calling
140          * cl_req_slice_add().
141          *
142          * \see osc_req_init(), lov_req_init(), lovsub_req_init()
143          * \see ccc_req_init()
144          */
145         int (*cdo_req_init)(const struct lu_env *env, struct cl_device *dev,
146                             struct cl_req *req);
147 };
148
149 /**
150  * Device in the client stack.
151  *
152  * \see ccc_device, lov_device, lovsub_device, osc_device
153  */
154 struct cl_device {
155         /** Super-class. */
156         struct lu_device                   cd_lu_dev;
157         /** Per-layer operation vector. */
158         const struct cl_device_operations *cd_ops;
159 };
160
161 /** \addtogroup cl_object cl_object
162  * @{ */
163 /**
164  * "Data attributes" of cl_object. Data attributes can be updated
165  * independently for a sub-object, and top-object's attributes are calculated
166  * from sub-objects' ones.
167  */
168 struct cl_attr {
169         /** Object size, in bytes */
170         loff_t cat_size;
171         /**
172          * Known minimal size, in bytes.
173          *
174          * This is only valid when at least one DLM lock is held.
175          */
176         loff_t cat_kms;
177         /** Modification time. Measured in seconds since epoch. */
178         time_t cat_mtime;
179         /** Access time. Measured in seconds since epoch. */
180         time_t cat_atime;
181         /** Change time. Measured in seconds since epoch. */
182         time_t cat_ctime;
183         /**
184          * Blocks allocated to this cl_object on the server file system.
185          *
186          * \todo XXX An interface for block size is needed.
187          */
188         __u64  cat_blocks;
189         /**
190          * User identifier for quota purposes.
191          */
192         uid_t  cat_uid;
193         /**
194          * Group identifier for quota purposes.
195          */
196         gid_t  cat_gid;
197 };
198
199 /**
200  * Fields in cl_attr that are being set.
201  */
202 enum cl_attr_valid {
203         CAT_SIZE   = 1 << 0,
204         CAT_KMS    = 1 << 1,
205         CAT_MTIME  = 1 << 3,
206         CAT_ATIME  = 1 << 4,
207         CAT_CTIME  = 1 << 5,
208         CAT_BLOCKS = 1 << 6,
209         CAT_UID    = 1 << 7,
210         CAT_GID    = 1 << 8
211 };
212
213 /**
214  * Sub-class of lu_object with methods common for objects on the client
215  * stacks.
216  *
217  * cl_object: represents a regular file system object, both a file and a
218  *    stripe. cl_object is based on lu_object: it is identified by a fid,
219  *    layered, cached, hashed, and lrued. Important distinction with the server
220  *    side, where md_object and dt_object are used, is that cl_object "fans out"
221  *    at the lov/sns level: depending on the file layout, single file is
222  *    represented as a set of "sub-objects" (stripes). At the implementation
223  *    level, struct lov_object contains an array of cl_objects. Each sub-object
224  *    is a full-fledged cl_object, having its fid, living in the lru and hash
225  *    table.
226  *
227  *    This leads to the next important difference with the server side: on the
228  *    client, it's quite usual to have objects with the different sequence of
229  *    layers. For example, typical top-object is composed of the following
230  *    layers:
231  *
232  *        - vvp
233  *        - lov
234  *
235  *    whereas its sub-objects are composed of
236  *
237  *        - lovsub
238  *        - osc
239  *
240  *    layers. Here "lovsub" is a mostly dummy layer, whose purpose is to keep
241  *    track of the object-subobject relationship.
242  *
243  *    Sub-objects are not cached independently: when top-object is about to
244  *    be discarded from the memory, all its sub-objects are torn-down and
245  *    destroyed too.
246  *
247  * \see ccc_object, lov_object, lovsub_object, osc_object
248  */
249 struct cl_object {
250         /** super class */
251         struct lu_object                   co_lu;
252         /** per-object-layer operations */
253         const struct cl_object_operations *co_ops;
254 };
255
256 /**
257  * Description of the client object configuration. This is used for the
258  * creation of a new client object that is identified by a more state than
259  * fid.
260  */
261 struct cl_object_conf {
262         /** Super-class. */
263         struct lu_object_conf     coc_lu;
264         union {
265                 /**
266                  * Object layout. This is consumed by lov.
267                  */
268                 struct lustre_md *coc_md;
269                 /**
270                  * Description of particular stripe location in the
271                  * cluster. This is consumed by osc.
272                  */
273                 struct lov_oinfo *coc_oinfo;
274         } u;
275         /**
276          * VFS inode. This is consumed by vvp.
277          */
278         struct inode             *coc_inode;
279         /**
280          * Layout lock handle.
281          */
282         struct ldlm_lock         *coc_lock;
283         /**
284          * Operation to handle layout, OBJECT_CONF_XYZ.
285          */
286         int                       coc_opc;
287 };
288
289 enum {
290         /** configure layout, set up a new stripe, must be called while
291          * holding layout lock. */
292         OBJECT_CONF_SET = 0,
293         /** invalidate the current stripe configuration due to losing
294          * layout lock. */
295         OBJECT_CONF_INVALIDATE = 1,
296         /** wait for old layout to go away so that new layout can be
297          * set up. */
298         OBJECT_CONF_WAIT = 2
299 };
300
301 /**
302  * Operations implemented for each cl object layer.
303  *
304  * \see vvp_ops, lov_ops, lovsub_ops, osc_ops
305  */
306 struct cl_object_operations {
307         /**
308          * Initialize page slice for this layer. Called top-to-bottom through
309          * every object layer when a new cl_page is instantiated. Layer
310          * keeping private per-page data, or requiring its own page operations
311          * vector should allocate these data here, and attach then to the page
312          * by calling cl_page_slice_add(). \a vmpage is locked (in the VM
313          * sense). Optional.
314          *
315          * \retval NULL success.
316          *
317          * \retval ERR_PTR(errno) failure code.
318          *
319          * \retval valid-pointer pointer to already existing referenced page
320          *         to be used instead of newly created.
321          */
322         struct cl_page *(*coo_page_init)(const struct lu_env *env,
323                                          struct cl_object *obj,
324                                          struct cl_page *page,
325                                          cfs_page_t *vmpage);
326         /**
327          * Initialize lock slice for this layer. Called top-to-bottom through
328          * every object layer when a new cl_lock is instantiated. Layer
329          * keeping private per-lock data, or requiring its own lock operations
330          * vector should allocate these data here, and attach then to the lock
331          * by calling cl_lock_slice_add(). Mandatory.
332          */
333         int  (*coo_lock_init)(const struct lu_env *env,
334                               struct cl_object *obj, struct cl_lock *lock,
335                               const struct cl_io *io);
336         /**
337          * Initialize io state for a given layer.
338          *
339          * called top-to-bottom once per io existence to initialize io
340          * state. If layer wants to keep some state for this type of io, it
341          * has to embed struct cl_io_slice in lu_env::le_ses, and register
342          * slice with cl_io_slice_add(). It is guaranteed that all threads
343          * participating in this io share the same session.
344          */
345         int  (*coo_io_init)(const struct lu_env *env,
346                             struct cl_object *obj, struct cl_io *io);
347         /**
348          * Fill portion of \a attr that this layer controls. This method is
349          * called top-to-bottom through all object layers.
350          *
351          * \pre cl_object_header::coh_attr_guard of the top-object is locked.
352          *
353          * \return   0: to continue
354          * \return +ve: to stop iterating through layers (but 0 is returned
355          * from enclosing cl_object_attr_get())
356          * \return -ve: to signal error
357          */
358         int (*coo_attr_get)(const struct lu_env *env, struct cl_object *obj,
359                             struct cl_attr *attr);
360         /**
361          * Update attributes.
362          *
363          * \a valid is a bitmask composed from enum #cl_attr_valid, and
364          * indicating what attributes are to be set.
365          *
366          * \pre cl_object_header::coh_attr_guard of the top-object is locked.
367          *
368          * \return the same convention as for
369          * cl_object_operations::coo_attr_get() is used.
370          */
371         int (*coo_attr_set)(const struct lu_env *env, struct cl_object *obj,
372                             const struct cl_attr *attr, unsigned valid);
373         /**
374          * Update object configuration. Called top-to-bottom to modify object
375          * configuration.
376          *
377          * XXX error conditions and handling.
378          */
379         int (*coo_conf_set)(const struct lu_env *env, struct cl_object *obj,
380                             const struct cl_object_conf *conf);
381         /**
382          * Glimpse ast. Executed when glimpse ast arrives for a lock on this
383          * object. Layers are supposed to fill parts of \a lvb that will be
384          * shipped to the glimpse originator as a glimpse result.
385          *
386          * \see ccc_object_glimpse(), lovsub_object_glimpse(),
387          * \see osc_object_glimpse()
388          */
389         int (*coo_glimpse)(const struct lu_env *env,
390                            const struct cl_object *obj, struct ost_lvb *lvb);
391 };
392
393 /**
394  * Extended header for client object.
395  */
396 struct cl_object_header {
397         /** Standard lu_object_header. cl_object::co_lu::lo_header points
398          * here. */
399         struct lu_object_header  coh_lu;
400         /** \name locks
401          * \todo XXX move locks below to the separate cache-lines, they are
402          * mostly useless otherwise.
403          */
404         /** @{ */
405         /** Lock protecting page tree. */
406         spinlock_t               coh_page_guard;
407         /** Lock protecting lock list. */
408         spinlock_t               coh_lock_guard;
409         /** @} locks */
410         /** Radix tree of cl_page's, cached for this object. */
411         struct radix_tree_root   coh_tree;
412         /** # of pages in radix tree. */
413         unsigned long            coh_pages;
414         /** List of cl_lock's granted for this object. */
415         cfs_list_t               coh_locks;
416
417         /**
418          * Parent object. It is assumed that an object has a well-defined
419          * parent, but not a well-defined child (there may be multiple
420          * sub-objects, for the same top-object). cl_object_header::coh_parent
421          * field allows certain code to be written generically, without
422          * limiting possible cl_object layouts unduly.
423          */
424         struct cl_object_header *coh_parent;
425         /**
426          * Protects consistency between cl_attr of parent object and
427          * attributes of sub-objects, that the former is calculated ("merged")
428          * from.
429          *
430          * \todo XXX this can be read/write lock if needed.
431          */
432         spinlock_t               coh_attr_guard;
433         /**
434          * Number of objects above this one: 0 for a top-object, 1 for its
435          * sub-object, etc.
436          */
437         unsigned                 coh_nesting;
438 };
439
440 /**
441  * Helper macro: iterate over all layers of the object \a obj, assigning every
442  * layer top-to-bottom to \a slice.
443  */
444 #define cl_object_for_each(slice, obj)                                      \
445         cfs_list_for_each_entry((slice),                                    \
446                                 &(obj)->co_lu.lo_header->loh_layers,        \
447                                 co_lu.lo_linkage)
448 /**
449  * Helper macro: iterate over all layers of the object \a obj, assigning every
450  * layer bottom-to-top to \a slice.
451  */
452 #define cl_object_for_each_reverse(slice, obj)                               \
453         cfs_list_for_each_entry_reverse((slice),                             \
454                                         &(obj)->co_lu.lo_header->loh_layers, \
455                                         co_lu.lo_linkage)
456 /** @} cl_object */
457
458 #ifndef pgoff_t
459 #define pgoff_t unsigned long
460 #endif
461
462 #define CL_PAGE_EOF ((pgoff_t)~0ull)
463
464 /** \addtogroup cl_page cl_page
465  * @{ */
466
467 /** \struct cl_page
468  * Layered client page.
469  *
470  * cl_page: represents a portion of a file, cached in the memory. All pages
471  *    of the given file are of the same size, and are kept in the radix tree
472  *    hanging off the cl_object. cl_page doesn't fan out, but as sub-objects
473  *    of the top-level file object are first class cl_objects, they have their
474  *    own radix trees of pages and hence page is implemented as a sequence of
475  *    struct cl_pages's, linked into double-linked list through
476  *    cl_page::cp_parent and cl_page::cp_child pointers, each residing in the
477  *    corresponding radix tree at the corresponding logical offset.
478  *
479  * cl_page is associated with VM page of the hosting environment (struct
480  *    page in Linux kernel, for example), cfs_page_t. It is assumed, that this
481  *    association is implemented by one of cl_page layers (top layer in the
482  *    current design) that
483  *
484  *        - intercepts per-VM-page call-backs made by the environment (e.g.,
485  *          memory pressure),
486  *
487  *        - translates state (page flag bits) and locking between lustre and
488  *          environment.
489  *
490  *    The association between cl_page and cfs_page_t is immutable and
491  *    established when cl_page is created.
492  *
493  * cl_page can be "owned" by a particular cl_io (see below), guaranteeing
494  *    this io an exclusive access to this page w.r.t. other io attempts and
495  *    various events changing page state (such as transfer completion, or
496  *    eviction of the page from the memory). Note, that in general cl_io
497  *    cannot be identified with a particular thread, and page ownership is not
498  *    exactly equal to the current thread holding a lock on the page. Layer
499  *    implementing association between cl_page and cfs_page_t has to implement
500  *    ownership on top of available synchronization mechanisms.
501  *
502  *    While lustre client maintains the notion of an page ownership by io,
503  *    hosting MM/VM usually has its own page concurrency control
504  *    mechanisms. For example, in Linux, page access is synchronized by the
505  *    per-page PG_locked bit-lock, and generic kernel code (generic_file_*())
506  *    takes care to acquire and release such locks as necessary around the
507  *    calls to the file system methods (->readpage(), ->prepare_write(),
508  *    ->commit_write(), etc.). This leads to the situation when there are two
509  *    different ways to own a page in the client:
510  *
511  *        - client code explicitly and voluntary owns the page (cl_page_own());
512  *
513  *        - VM locks a page and then calls the client, that has "to assume"
514  *          the ownership from the VM (cl_page_assume()).
515  *
516  *    Dual methods to release ownership are cl_page_disown() and
517  *    cl_page_unassume().
518  *
519  * cl_page is reference counted (cl_page::cp_ref). When reference counter
520  *    drops to 0, the page is returned to the cache, unless it is in
521  *    cl_page_state::CPS_FREEING state, in which case it is immediately
522  *    destroyed.
523  *
524  *    The general logic guaranteeing the absence of "existential races" for
525  *    pages is the following:
526  *
527  *        - there are fixed known ways for a thread to obtain a new reference
528  *          to a page:
529  *
530  *            - by doing a lookup in the cl_object radix tree, protected by the
531  *              spin-lock;
532  *
533  *            - by starting from VM-locked cfs_page_t and following some
534  *              hosting environment method (e.g., following ->private pointer in
535  *              the case of Linux kernel), see cl_vmpage_page();
536  *
537  *        - when the page enters cl_page_state::CPS_FREEING state, all these
538  *          ways are severed with the proper synchronization
539  *          (cl_page_delete());
540  *
541  *        - entry into cl_page_state::CPS_FREEING is serialized by the VM page
542  *          lock;
543  *
544  *        - no new references to the page in cl_page_state::CPS_FREEING state
545  *          are allowed (checked in cl_page_get()).
546  *
547  *    Together this guarantees that when last reference to a
548  *    cl_page_state::CPS_FREEING page is released, it is safe to destroy the
549  *    page, as neither references to it can be acquired at that point, nor
550  *    ones exist.
551  *
552  * cl_page is a state machine. States are enumerated in enum
553  *    cl_page_state. Possible state transitions are enumerated in
554  *    cl_page_state_set(). State transition process (i.e., actual changing of
555  *    cl_page::cp_state field) is protected by the lock on the underlying VM
556  *    page.
557  *
558  * Linux Kernel implementation.
559  *
560  *    Binding between cl_page and cfs_page_t (which is a typedef for
561  *    struct page) is implemented in the vvp layer. cl_page is attached to the
562  *    ->private pointer of the struct page, together with the setting of
563  *    PG_private bit in page->flags, and acquiring additional reference on the
564  *    struct page (much like struct buffer_head, or any similar file system
565  *    private data structures).
566  *
567  *    PG_locked lock is used to implement both ownership and transfer
568  *    synchronization, that is, page is VM-locked in CPS_{OWNED,PAGE{IN,OUT}}
569  *    states. No additional references are acquired for the duration of the
570  *    transfer.
571  *
572  * \warning *THIS IS NOT* the behavior expected by the Linux kernel, where
573  *          write-out is "protected" by the special PG_writeback bit.
574  */
575
576 /**
577  * States of cl_page. cl_page.c assumes particular order here.
578  *
579  * The page state machine is rather crude, as it doesn't recognize finer page
580  * states like "dirty" or "up to date". This is because such states are not
581  * always well defined for the whole stack (see, for example, the
582  * implementation of the read-ahead, that hides page up-to-dateness to track
583  * cache hits accurately). Such sub-states are maintained by the layers that
584  * are interested in them.
585  */
586 enum cl_page_state {
587         /**
588          * Page is in the cache, un-owned. Page leaves cached state in the
589          * following cases:
590          *
591          *     - [cl_page_state::CPS_OWNED] io comes across the page and
592          *     owns it;
593          *
594          *     - [cl_page_state::CPS_PAGEOUT] page is dirty, the
595          *     req-formation engine decides that it wants to include this page
596          *     into an cl_req being constructed, and yanks it from the cache;
597          *
598          *     - [cl_page_state::CPS_FREEING] VM callback is executed to
599          *     evict the page form the memory;
600          *
601          * \invariant cl_page::cp_owner == NULL && cl_page::cp_req == NULL
602          */
603         CPS_CACHED,
604         /**
605          * Page is exclusively owned by some cl_io. Page may end up in this
606          * state as a result of
607          *
608          *     - io creating new page and immediately owning it;
609          *
610          *     - [cl_page_state::CPS_CACHED] io finding existing cached page
611          *     and owning it;
612          *
613          *     - [cl_page_state::CPS_OWNED] io finding existing owned page
614          *     and waiting for owner to release the page;
615          *
616          * Page leaves owned state in the following cases:
617          *
618          *     - [cl_page_state::CPS_CACHED] io decides to leave the page in
619          *     the cache, doing nothing;
620          *
621          *     - [cl_page_state::CPS_PAGEIN] io starts read transfer for
622          *     this page;
623          *
624          *     - [cl_page_state::CPS_PAGEOUT] io starts immediate write
625          *     transfer for this page;
626          *
627          *     - [cl_page_state::CPS_FREEING] io decides to destroy this
628          *     page (e.g., as part of truncate or extent lock cancellation).
629          *
630          * \invariant cl_page::cp_owner != NULL && cl_page::cp_req == NULL
631          */
632         CPS_OWNED,
633         /**
634          * Page is being written out, as a part of a transfer. This state is
635          * entered when req-formation logic decided that it wants this page to
636          * be sent through the wire _now_. Specifically, it means that once
637          * this state is achieved, transfer completion handler (with either
638          * success or failure indication) is guaranteed to be executed against
639          * this page independently of any locks and any scheduling decisions
640          * made by the hosting environment (that effectively means that the
641          * page is never put into cl_page_state::CPS_PAGEOUT state "in
642          * advance". This property is mentioned, because it is important when
643          * reasoning about possible dead-locks in the system). The page can
644          * enter this state as a result of
645          *
646          *     - [cl_page_state::CPS_OWNED] an io requesting an immediate
647          *     write-out of this page, or
648          *
649          *     - [cl_page_state::CPS_CACHED] req-forming engine deciding
650          *     that it has enough dirty pages cached to issue a "good"
651          *     transfer.
652          *
653          * The page leaves cl_page_state::CPS_PAGEOUT state when the transfer
654          * is completed---it is moved into cl_page_state::CPS_CACHED state.
655          *
656          * Underlying VM page is locked for the duration of transfer.
657          *
658          * \invariant: cl_page::cp_owner == NULL && cl_page::cp_req != NULL
659          */
660         CPS_PAGEOUT,
661         /**
662          * Page is being read in, as a part of a transfer. This is quite
663          * similar to the cl_page_state::CPS_PAGEOUT state, except that
664          * read-in is always "immediate"---there is no such thing a sudden
665          * construction of read cl_req from cached, presumably not up to date,
666          * pages.
667          *
668          * Underlying VM page is locked for the duration of transfer.
669          *
670          * \invariant: cl_page::cp_owner == NULL && cl_page::cp_req != NULL
671          */
672         CPS_PAGEIN,
673         /**
674          * Page is being destroyed. This state is entered when client decides
675          * that page has to be deleted from its host object, as, e.g., a part
676          * of truncate.
677          *
678          * Once this state is reached, there is no way to escape it.
679          *
680          * \invariant: cl_page::cp_owner == NULL && cl_page::cp_req == NULL
681          */
682         CPS_FREEING,
683         CPS_NR
684 };
685
686 enum cl_page_type {
687         /** Host page, the page is from the host inode which the cl_page
688          * belongs to. */
689         CPT_CACHEABLE = 1,
690
691         /** Transient page, the transient cl_page is used to bind a cl_page
692          *  to vmpage which is not belonging to the same object of cl_page.
693          *  it is used in DirectIO, lockless IO and liblustre. */
694         CPT_TRANSIENT,
695 };
696
697 /**
698  * Flags maintained for every cl_page.
699  */
700 enum cl_page_flags {
701         /**
702          * Set when pagein completes. Used for debugging (read completes at
703          * most once for a page).
704          */
705         CPF_READ_COMPLETED = 1 << 0
706 };
707
708 /**
709  * Fields are protected by the lock on cfs_page_t, except for atomics and
710  * immutables.
711  *
712  * \invariant Data type invariants are in cl_page_invariant(). Basically:
713  * cl_page::cp_parent and cl_page::cp_child are a well-formed double-linked
714  * list, consistent with the parent/child pointers in the cl_page::cp_obj and
715  * cl_page::cp_owner (when set).
716  */
717 struct cl_page {
718         /** Reference counter. */
719         cfs_atomic_t             cp_ref;
720         /** An object this page is a part of. Immutable after creation. */
721         struct cl_object        *cp_obj;
722         /** Logical page index within the object. Immutable after creation. */
723         pgoff_t                  cp_index;
724         /** List of slices. Immutable after creation. */
725         cfs_list_t               cp_layers;
726         /** Parent page, NULL for top-level page. Immutable after creation. */
727         struct cl_page          *cp_parent;
728         /** Lower-layer page. NULL for bottommost page. Immutable after
729          * creation. */
730         struct cl_page          *cp_child;
731         /**
732          * Page state. This field is const to avoid accidental update, it is
733          * modified only internally within cl_page.c. Protected by a VM lock.
734          */
735         const enum cl_page_state cp_state;
736         /** Linkage of pages within group. Protected by cl_page::cp_mutex. */
737         cfs_list_t              cp_batch;
738         /** Mutex serializing membership of a page in a batch. */
739         struct mutex            cp_mutex;
740         /** Linkage of pages within cl_req. */
741         cfs_list_t               cp_flight;
742         /** Transfer error. */
743         int                      cp_error;
744
745         /**
746          * Page type. Only CPT_TRANSIENT is used so far. Immutable after
747          * creation.
748          */
749         enum cl_page_type        cp_type;
750
751         /**
752          * Owning IO in cl_page_state::CPS_OWNED state. Sub-page can be owned
753          * by sub-io. Protected by a VM lock.
754          */
755         struct cl_io            *cp_owner;
756         /**
757          * Debug information, the task is owning the page.
758          */
759         cfs_task_t              *cp_task;
760         /**
761          * Owning IO request in cl_page_state::CPS_PAGEOUT and
762          * cl_page_state::CPS_PAGEIN states. This field is maintained only in
763          * the top-level pages. Protected by a VM lock.
764          */
765         struct cl_req           *cp_req;
766         /** List of references to this page, for debugging. */
767         struct lu_ref            cp_reference;
768         /** Link to an object, for debugging. */
769         struct lu_ref_link      *cp_obj_ref;
770         /** Link to a queue, for debugging. */
771         struct lu_ref_link      *cp_queue_ref;
772         /** Per-page flags from enum cl_page_flags. Protected by a VM lock. */
773         unsigned                 cp_flags;
774         /** Assigned if doing a sync_io */
775         struct cl_sync_io       *cp_sync_io;
776 };
777
778 /**
779  * Per-layer part of cl_page.
780  *
781  * \see ccc_page, lov_page, osc_page
782  */
783 struct cl_page_slice {
784         struct cl_page                  *cpl_page;
785         /**
786          * Object slice corresponding to this page slice. Immutable after
787          * creation.
788          */
789         struct cl_object                *cpl_obj;
790         const struct cl_page_operations *cpl_ops;
791         /** Linkage into cl_page::cp_layers. Immutable after creation. */
792         cfs_list_t                       cpl_linkage;
793 };
794
795 /**
796  * Lock mode. For the client extent locks.
797  *
798  * \warning: cl_lock_mode_match() assumes particular ordering here.
799  * \ingroup cl_lock
800  */
801 enum cl_lock_mode {
802         /**
803          * Mode of a lock that protects no data, and exists only as a
804          * placeholder. This is used for `glimpse' requests. A phantom lock
805          * might get promoted to real lock at some point.
806          */
807         CLM_PHANTOM,
808         CLM_READ,
809         CLM_WRITE,
810         CLM_GROUP
811 };
812
813 /**
814  * Requested transfer type.
815  * \ingroup cl_req
816  */
817 enum cl_req_type {
818         CRT_READ,
819         CRT_WRITE,
820         CRT_NR
821 };
822
823 /**
824  * Per-layer page operations.
825  *
826  * Methods taking an \a io argument are for the activity happening in the
827  * context of given \a io. Page is assumed to be owned by that io, except for
828  * the obvious cases (like cl_page_operations::cpo_own()).
829  *
830  * \see vvp_page_ops, lov_page_ops, osc_page_ops
831  */
832 struct cl_page_operations {
833         /**
834          * cl_page<->cfs_page_t methods. Only one layer in the stack has to
835          * implement these. Current code assumes that this functionality is
836          * provided by the topmost layer, see cl_page_disown0() as an example.
837          */
838
839         /**
840          * \return the underlying VM page. Optional.
841          */
842         cfs_page_t *(*cpo_vmpage)(const struct lu_env *env,
843                                   const struct cl_page_slice *slice);
844         /**
845          * Called when \a io acquires this page into the exclusive
846          * ownership. When this method returns, it is guaranteed that the is
847          * not owned by other io, and no transfer is going on against
848          * it. Optional.
849          *
850          * \see cl_page_own()
851          * \see vvp_page_own(), lov_page_own()
852          */
853         int  (*cpo_own)(const struct lu_env *env,
854                         const struct cl_page_slice *slice,
855                         struct cl_io *io, int nonblock);
856         /** Called when ownership it yielded. Optional.
857          *
858          * \see cl_page_disown()
859          * \see vvp_page_disown()
860          */
861         void (*cpo_disown)(const struct lu_env *env,
862                            const struct cl_page_slice *slice, struct cl_io *io);
863         /**
864          * Called for a page that is already "owned" by \a io from VM point of
865          * view. Optional.
866          *
867          * \see cl_page_assume()
868          * \see vvp_page_assume(), lov_page_assume()
869          */
870         void (*cpo_assume)(const struct lu_env *env,
871                            const struct cl_page_slice *slice, struct cl_io *io);
872         /** Dual to cl_page_operations::cpo_assume(). Optional. Called
873          * bottom-to-top when IO releases a page without actually unlocking
874          * it.
875          *
876          * \see cl_page_unassume()
877          * \see vvp_page_unassume()
878          */
879         void (*cpo_unassume)(const struct lu_env *env,
880                              const struct cl_page_slice *slice,
881                              struct cl_io *io);
882         /**
883          * Announces whether the page contains valid data or not by \a uptodate.
884          *
885          * \see cl_page_export()
886          * \see vvp_page_export()
887          */
888         void  (*cpo_export)(const struct lu_env *env,
889                             const struct cl_page_slice *slice, int uptodate);
890         /**
891          * Unmaps page from the user space (if it is mapped).
892          *
893          * \see cl_page_unmap()
894          * \see vvp_page_unmap()
895          */
896         int (*cpo_unmap)(const struct lu_env *env,
897                          const struct cl_page_slice *slice, struct cl_io *io);
898         /**
899          * Checks whether underlying VM page is locked (in the suitable
900          * sense). Used for assertions.
901          *
902          * \retval    -EBUSY: page is protected by a lock of a given mode;
903          * \retval  -ENODATA: page is not protected by a lock;
904          * \retval         0: this layer cannot decide. (Should never happen.)
905          */
906         int (*cpo_is_vmlocked)(const struct lu_env *env,
907                                const struct cl_page_slice *slice);
908         /**
909          * Page destruction.
910          */
911
912         /**
913          * Called when page is truncated from the object. Optional.
914          *
915          * \see cl_page_discard()
916          * \see vvp_page_discard(), osc_page_discard()
917          */
918         void (*cpo_discard)(const struct lu_env *env,
919                             const struct cl_page_slice *slice,
920                             struct cl_io *io);
921         /**
922          * Called when page is removed from the cache, and is about to being
923          * destroyed. Optional.
924          *
925          * \see cl_page_delete()
926          * \see vvp_page_delete(), osc_page_delete()
927          */
928         void (*cpo_delete)(const struct lu_env *env,
929                            const struct cl_page_slice *slice);
930         /** Destructor. Frees resources and slice itself. */
931         void (*cpo_fini)(const struct lu_env *env,
932                          struct cl_page_slice *slice);
933
934         /**
935          * Checks whether the page is protected by a cl_lock. This is a
936          * per-layer method, because certain layers have ways to check for the
937          * lock much more efficiently than through the generic locks scan, or
938          * implement locking mechanisms separate from cl_lock, e.g.,
939          * LL_FILE_GROUP_LOCKED in vvp. If \a pending is true, check for locks
940          * being canceled, or scheduled for cancellation as soon as the last
941          * user goes away, too.
942          *
943          * \retval    -EBUSY: page is protected by a lock of a given mode;
944          * \retval  -ENODATA: page is not protected by a lock;
945          * \retval         0: this layer cannot decide.
946          *
947          * \see cl_page_is_under_lock()
948          */
949         int (*cpo_is_under_lock)(const struct lu_env *env,
950                                  const struct cl_page_slice *slice,
951                                  struct cl_io *io);
952
953         /**
954          * Optional debugging helper. Prints given page slice.
955          *
956          * \see cl_page_print()
957          */
958         int (*cpo_print)(const struct lu_env *env,
959                          const struct cl_page_slice *slice,
960                          void *cookie, lu_printer_t p);
961         /**
962          * \name transfer
963          *
964          * Transfer methods. See comment on cl_req for a description of
965          * transfer formation and life-cycle.
966          *
967          * @{
968          */
969         /**
970          * Request type dependent vector of operations.
971          *
972          * Transfer operations depend on transfer mode (cl_req_type). To avoid
973          * passing transfer mode to each and every of these methods, and to
974          * avoid branching on request type inside of the methods, separate
975          * methods for cl_req_type:CRT_READ and cl_req_type:CRT_WRITE are
976          * provided. That is, method invocation usually looks like
977          *
978          *         slice->cp_ops.io[req->crq_type].cpo_method(env, slice, ...);
979          */
980         struct {
981                 /**
982                  * Called when a page is submitted for a transfer as a part of
983                  * cl_page_list.
984                  *
985                  * \return    0         : page is eligible for submission;
986                  * \return    -EALREADY : skip this page;
987                  * \return    -ve       : error.
988                  *
989                  * \see cl_page_prep()
990                  */
991                 int  (*cpo_prep)(const struct lu_env *env,
992                                  const struct cl_page_slice *slice,
993                                  struct cl_io *io);
994                 /**
995                  * Completion handler. This is guaranteed to be eventually
996                  * fired after cl_page_operations::cpo_prep() or
997                  * cl_page_operations::cpo_make_ready() call.
998                  *
999                  * This method can be called in a non-blocking context. It is
1000                  * guaranteed however, that the page involved and its object
1001                  * are pinned in memory (and, hence, calling cl_page_put() is
1002                  * safe).
1003                  *
1004                  * \see cl_page_completion()
1005                  */
1006                 void (*cpo_completion)(const struct lu_env *env,
1007                                        const struct cl_page_slice *slice,
1008                                        int ioret);
1009                 /**
1010                  * Called when cached page is about to be added to the
1011                  * cl_req as a part of req formation.
1012                  *
1013                  * \return    0       : proceed with this page;
1014                  * \return    -EAGAIN : skip this page;
1015                  * \return    -ve     : error.
1016                  *
1017                  * \see cl_page_make_ready()
1018                  */
1019                 int  (*cpo_make_ready)(const struct lu_env *env,
1020                                        const struct cl_page_slice *slice);
1021                 /**
1022                  * Announce that this page is to be written out
1023                  * opportunistically, that is, page is dirty, it is not
1024                  * necessary to start write-out transfer right now, but
1025                  * eventually page has to be written out.
1026                  *
1027                  * Main caller of this is the write path (see
1028                  * vvp_io_commit_write()), using this method to build a
1029                  * "transfer cache" from which large transfers are then
1030                  * constructed by the req-formation engine.
1031                  *
1032                  * \todo XXX it would make sense to add page-age tracking
1033                  * semantics here, and to oblige the req-formation engine to
1034                  * send the page out not later than it is too old.
1035                  *
1036                  * \see cl_page_cache_add()
1037                  */
1038                 int  (*cpo_cache_add)(const struct lu_env *env,
1039                                       const struct cl_page_slice *slice,
1040                                       struct cl_io *io);
1041         } io[CRT_NR];
1042         /**
1043          * Tell transfer engine that only [to, from] part of a page should be
1044          * transmitted.
1045          *
1046          * This is used for immediate transfers.
1047          *
1048          * \todo XXX this is not very good interface. It would be much better
1049          * if all transfer parameters were supplied as arguments to
1050          * cl_io_operations::cio_submit() call, but it is not clear how to do
1051          * this for page queues.
1052          *
1053          * \see cl_page_clip()
1054          */
1055         void (*cpo_clip)(const struct lu_env *env,
1056                          const struct cl_page_slice *slice,
1057                          int from, int to);
1058         /**
1059          * \pre  the page was queued for transferring.
1060          * \post page is removed from client's pending list, or -EBUSY
1061          *       is returned if it has already been in transferring.
1062          *
1063          * This is one of seldom page operation which is:
1064          * 0. called from top level;
1065          * 1. don't have vmpage locked;
1066          * 2. every layer should synchronize execution of its ->cpo_cancel()
1067          *    with completion handlers. Osc uses client obd lock for this
1068          *    purpose. Based on there is no vvp_page_cancel and
1069          *    lov_page_cancel(), cpo_cancel is defacto protected by client lock.
1070          *
1071          * \see osc_page_cancel().
1072          */
1073         int (*cpo_cancel)(const struct lu_env *env,
1074                           const struct cl_page_slice *slice);
1075         /**
1076          * Write out a page by kernel. This is only called by ll_writepage
1077          * right now.
1078          *
1079          * \see cl_page_flush()
1080          */
1081         int (*cpo_flush)(const struct lu_env *env,
1082                          const struct cl_page_slice *slice,
1083                          struct cl_io *io);
1084         /** @} transfer */
1085 };
1086
1087 /**
1088  * Helper macro, dumping detailed information about \a page into a log.
1089  */
1090 #define CL_PAGE_DEBUG(mask, env, page, format, ...)                     \
1091 do {                                                                    \
1092         LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, mask, NULL);                \
1093                                                                         \
1094         if (cfs_cdebug_show(mask, DEBUG_SUBSYSTEM)) {                   \
1095                 cl_page_print(env, &msgdata, lu_cdebug_printer, page);  \
1096                 CDEBUG(mask, format , ## __VA_ARGS__);                  \
1097         }                                                               \
1098 } while (0)
1099
1100 /**
1101  * Helper macro, dumping shorter information about \a page into a log.
1102  */
1103 #define CL_PAGE_HEADER(mask, env, page, format, ...)                          \
1104 do {                                                                          \
1105         LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, mask, NULL);                      \
1106                                                                               \
1107         if (cfs_cdebug_show(mask, DEBUG_SUBSYSTEM)) {                         \
1108                 cl_page_header_print(env, &msgdata, lu_cdebug_printer, page); \
1109                 CDEBUG(mask, format , ## __VA_ARGS__);                        \
1110         }                                                                     \
1111 } while (0)
1112
1113 static inline int __page_in_use(const struct cl_page *page, int refc)
1114 {
1115         if (page->cp_type == CPT_CACHEABLE)
1116                 ++refc;
1117         LASSERT(cfs_atomic_read(&page->cp_ref) > 0);
1118         return (cfs_atomic_read(&page->cp_ref) > refc);
1119 }
1120 #define cl_page_in_use(pg)       __page_in_use(pg, 1)
1121 #define cl_page_in_use_noref(pg) __page_in_use(pg, 0)
1122
1123 /** @} cl_page */
1124
1125 /** \addtogroup cl_lock cl_lock
1126  * @{ */
1127 /** \struct cl_lock
1128  *
1129  * Extent locking on the client.
1130  *
1131  * LAYERING
1132  *
1133  * The locking model of the new client code is built around
1134  *
1135  *        struct cl_lock
1136  *
1137  * data-type representing an extent lock on a regular file. cl_lock is a
1138  * layered object (much like cl_object and cl_page), it consists of a header
1139  * (struct cl_lock) and a list of layers (struct cl_lock_slice), linked to
1140  * cl_lock::cll_layers list through cl_lock_slice::cls_linkage.
1141  *
1142  * All locks for a given object are linked into cl_object_header::coh_locks
1143  * list (protected by cl_object_header::coh_lock_guard spin-lock) through
1144  * cl_lock::cll_linkage. Currently this list is not sorted in any way. We can
1145  * sort it in starting lock offset, or use altogether different data structure
1146  * like a tree.
1147  *
1148  * Typical cl_lock consists of the two layers:
1149  *
1150  *     - vvp_lock (vvp specific data), and
1151  *     - lov_lock (lov specific data).
1152  *
1153  * lov_lock contains an array of sub-locks. Each of these sub-locks is a
1154  * normal cl_lock: it has a header (struct cl_lock) and a list of layers:
1155  *
1156  *     - lovsub_lock, and
1157  *     - osc_lock
1158  *
1159  * Each sub-lock is associated with a cl_object (representing stripe
1160  * sub-object or the file to which top-level cl_lock is associated to), and is
1161  * linked into that cl_object::coh_locks. In this respect cl_lock is similar to
1162  * cl_object (that at lov layer also fans out into multiple sub-objects), and
1163  * is different from cl_page, that doesn't fan out (there is usually exactly
1164  * one osc_page for every vvp_page). We shall call vvp-lov portion of the lock
1165  * a "top-lock" and its lovsub-osc portion a "sub-lock".
1166  *
1167  * LIFE CYCLE
1168  *
1169  * cl_lock is reference counted. When reference counter drops to 0, lock is
1170  * placed in the cache, except when lock is in CLS_FREEING state. CLS_FREEING
1171  * lock is destroyed when last reference is released. Referencing between
1172  * top-lock and its sub-locks is described in the lov documentation module.
1173  *
1174  * STATE MACHINE
1175  *
1176  * Also, cl_lock is a state machine. This requires some clarification. One of
1177  * the goals of client IO re-write was to make IO path non-blocking, or at
1178  * least to make it easier to make it non-blocking in the future. Here
1179  * `non-blocking' means that when a system call (read, write, truncate)
1180  * reaches a situation where it has to wait for a communication with the
1181  * server, it should --instead of waiting-- remember its current state and
1182  * switch to some other work.  E.g,. instead of waiting for a lock enqueue,
1183  * client should proceed doing IO on the next stripe, etc. Obviously this is
1184  * rather radical redesign, and it is not planned to be fully implemented at
1185  * this time, instead we are putting some infrastructure in place, that would
1186  * make it easier to do asynchronous non-blocking IO easier in the
1187  * future. Specifically, where old locking code goes to sleep (waiting for
1188  * enqueue, for example), new code returns cl_lock_transition::CLO_WAIT. When
1189  * enqueue reply comes, its completion handler signals that lock state-machine
1190  * is ready to transit to the next state. There is some generic code in
1191  * cl_lock.c that sleeps, waiting for these signals. As a result, for users of
1192  * this cl_lock.c code, it looks like locking is done in normal blocking
1193  * fashion, and it the same time it is possible to switch to the non-blocking
1194  * locking (simply by returning cl_lock_transition::CLO_WAIT from cl_lock.c
1195  * functions).
1196  *
1197  * For a description of state machine states and transitions see enum
1198  * cl_lock_state.
1199  *
1200  * There are two ways to restrict a set of states which lock might move to:
1201  *
1202  *     - placing a "hold" on a lock guarantees that lock will not be moved
1203  *       into cl_lock_state::CLS_FREEING state until hold is released. Hold
1204  *       can be only acquired on a lock that is not in
1205  *       cl_lock_state::CLS_FREEING. All holds on a lock are counted in
1206  *       cl_lock::cll_holds. Hold protects lock from cancellation and
1207  *       destruction. Requests to cancel and destroy a lock on hold will be
1208  *       recorded, but only honored when last hold on a lock is released;
1209  *
1210  *     - placing a "user" on a lock guarantees that lock will not leave
1211  *       cl_lock_state::CLS_NEW, cl_lock_state::CLS_QUEUING,
1212  *       cl_lock_state::CLS_ENQUEUED and cl_lock_state::CLS_HELD set of
1213  *       states, once it enters this set. That is, if a user is added onto a
1214  *       lock in a state not from this set, it doesn't immediately enforce
1215  *       lock to move to this set, but once lock enters this set it will
1216  *       remain there until all users are removed. Lock users are counted in
1217  *       cl_lock::cll_users.
1218  *
1219  *       User is used to assure that lock is not canceled or destroyed while
1220  *       it is being enqueued, or actively used by some IO.
1221  *
1222  *       Currently, a user always comes with a hold (cl_lock_invariant()
1223  *       checks that a number of holds is not less than a number of users).
1224  *
1225  * CONCURRENCY
1226  *
1227  * This is how lock state-machine operates. struct cl_lock contains a mutex
1228  * cl_lock::cll_guard that protects struct fields.
1229  *
1230  *     - mutex is taken, and cl_lock::cll_state is examined.
1231  *
1232  *     - for every state there are possible target states where lock can move
1233  *       into. They are tried in order. Attempts to move into next state are
1234  *       done by _try() functions in cl_lock.c:cl_{enqueue,unlock,wait}_try().
1235  *
1236  *     - if the transition can be performed immediately, state is changed,
1237  *       and mutex is released.
1238  *
1239  *     - if the transition requires blocking, _try() function returns
1240  *       cl_lock_transition::CLO_WAIT. Caller unlocks mutex and goes to
1241  *       sleep, waiting for possibility of lock state change. It is woken
1242  *       up when some event occurs, that makes lock state change possible
1243  *       (e.g., the reception of the reply from the server), and repeats
1244  *       the loop.
1245  *
1246  * Top-lock and sub-lock has separate mutexes and the latter has to be taken
1247  * first to avoid dead-lock.
1248  *
1249  * To see an example of interaction of all these issues, take a look at the
1250  * lov_cl.c:lov_lock_enqueue() function. It is called as a part of
1251  * cl_enqueue_try(), and tries to advance top-lock to ENQUEUED state, by
1252  * advancing state-machines of its sub-locks (lov_lock_enqueue_one()). Note
1253  * also, that it uses trylock to grab sub-lock mutex to avoid dead-lock. It
1254  * also has to handle CEF_ASYNC enqueue, when sub-locks enqueues have to be
1255  * done in parallel, rather than one after another (this is used for glimpse
1256  * locks, that cannot dead-lock).
1257  *
1258  * INTERFACE AND USAGE
1259  *
1260  * struct cl_lock_operations provide a number of call-backs that are invoked
1261  * when events of interest occurs. Layers can intercept and handle glimpse,
1262  * blocking, cancel ASTs and a reception of the reply from the server.
1263  *
1264  * One important difference with the old client locking model is that new
1265  * client has a representation for the top-lock, whereas in the old code only
1266  * sub-locks existed as real data structures and file-level locks are
1267  * represented by "request sets" that are created and destroyed on each and
1268  * every lock creation.
1269  *
1270  * Top-locks are cached, and can be found in the cache by the system calls. It
1271  * is possible that top-lock is in cache, but some of its sub-locks were
1272  * canceled and destroyed. In that case top-lock has to be enqueued again
1273  * before it can be used.
1274  *
1275  * Overall process of the locking during IO operation is as following:
1276  *
1277  *     - once parameters for IO are setup in cl_io, cl_io_operations::cio_lock()
1278  *       is called on each layer. Responsibility of this method is to add locks,
1279  *       needed by a given layer into cl_io.ci_lockset.
1280  *
1281  *     - once locks for all layers were collected, they are sorted to avoid
1282  *       dead-locks (cl_io_locks_sort()), and enqueued.
1283  *
1284  *     - when all locks are acquired, IO is performed;
1285  *
1286  *     - locks are released into cache.
1287  *
1288  * Striping introduces major additional complexity into locking. The
1289  * fundamental problem is that it is generally unsafe to actively use (hold)
1290  * two locks on the different OST servers at the same time, as this introduces
1291  * inter-server dependency and can lead to cascading evictions.
1292  *
1293  * Basic solution is to sub-divide large read/write IOs into smaller pieces so
1294  * that no multi-stripe locks are taken (note that this design abandons POSIX
1295  * read/write semantics). Such pieces ideally can be executed concurrently. At
1296  * the same time, certain types of IO cannot be sub-divived, without
1297  * sacrificing correctness. This includes:
1298  *
1299  *  - O_APPEND write, where [0, EOF] lock has to be taken, to guarantee
1300  *  atomicity;
1301  *
1302  *  - ftruncate(fd, offset), where [offset, EOF] lock has to be taken.
1303  *
1304  * Also, in the case of read(fd, buf, count) or write(fd, buf, count), where
1305  * buf is a part of memory mapped Lustre file, a lock or locks protecting buf
1306  * has to be held together with the usual lock on [offset, offset + count].
1307  *
1308  * As multi-stripe locks have to be allowed, it makes sense to cache them, so
1309  * that, for example, a sequence of O_APPEND writes can proceed quickly
1310  * without going down to the individual stripes to do lock matching. On the
1311  * other hand, multi-stripe locks shouldn't be used by normal read/write
1312  * calls. To achieve this, every layer can implement ->clo_fits_into() method,
1313  * that is called by lock matching code (cl_lock_lookup()), and that can be
1314  * used to selectively disable matching of certain locks for certain IOs. For
1315  * exmaple, lov layer implements lov_lock_fits_into() that allow multi-stripe
1316  * locks to be matched only for truncates and O_APPEND writes.
1317  *
1318  * Interaction with DLM
1319  *
1320  * In the expected setup, cl_lock is ultimately backed up by a collection of
1321  * DLM locks (struct ldlm_lock). Association between cl_lock and DLM lock is
1322  * implemented in osc layer, that also matches DLM events (ASTs, cancellation,
1323  * etc.) into cl_lock_operation calls. See struct osc_lock for a more detailed
1324  * description of interaction with DLM.
1325  */
1326
1327 /**
1328  * Lock description.
1329  */
1330 struct cl_lock_descr {
1331         /** Object this lock is granted for. */
1332         struct cl_object *cld_obj;
1333         /** Index of the first page protected by this lock. */
1334         pgoff_t           cld_start;
1335         /** Index of the last page (inclusive) protected by this lock. */
1336         pgoff_t           cld_end;
1337         /** Group ID, for group lock */
1338         __u64             cld_gid;
1339         /** Lock mode. */
1340         enum cl_lock_mode cld_mode;
1341         /**
1342          * flags to enqueue lock. A combination of bit-flags from
1343          * enum cl_enq_flags.
1344          */
1345         __u32             cld_enq_flags;
1346 };
1347
1348 #define DDESCR "%s(%d):[%lu, %lu]"
1349 #define PDESCR(descr)                                                   \
1350         cl_lock_mode_name((descr)->cld_mode), (descr)->cld_mode,        \
1351         (descr)->cld_start, (descr)->cld_end
1352
1353 const char *cl_lock_mode_name(const enum cl_lock_mode mode);
1354
1355 /**
1356  * Lock state-machine states.
1357  *
1358  * \htmlonly
1359  * <pre>
1360  *
1361  * Possible state transitions:
1362  *
1363  *              +------------------>NEW
1364  *              |                    |
1365  *              |                    | cl_enqueue_try()
1366  *              |                    |
1367  *              |    cl_unuse_try()  V
1368  *              |  +--------------QUEUING (*)
1369  *              |  |                 |
1370  *              |  |                 | cl_enqueue_try()
1371  *              |  |                 |
1372  *              |  | cl_unuse_try()  V
1373  *    sub-lock  |  +-------------ENQUEUED (*)
1374  *    canceled  |  |                 |
1375  *              |  |                 | cl_wait_try()
1376  *              |  |                 |
1377  *              |  |                (R)
1378  *              |  |                 |
1379  *              |  |                 V
1380  *              |  |                HELD<---------+
1381  *              |  |                 |            |
1382  *              |  |                 |            | cl_use_try()
1383  *              |  |  cl_unuse_try() |            |
1384  *              |  |                 |            |
1385  *              |  |                 V         ---+ 
1386  *              |  +------------>INTRANSIT (D) <--+
1387  *              |                    |            |
1388  *              |     cl_unuse_try() |            | cached lock found
1389  *              |                    |            | cl_use_try()
1390  *              |                    |            |
1391  *              |                    V            |
1392  *              +------------------CACHED---------+
1393  *                                   |
1394  *                                  (C)
1395  *                                   |
1396  *                                   V
1397  *                                FREEING
1398  *
1399  * Legend:
1400  *
1401  *         In states marked with (*) transition to the same state (i.e., a loop
1402  *         in the diagram) is possible.
1403  *
1404  *         (R) is the point where Receive call-back is invoked: it allows layers
1405  *         to handle arrival of lock reply.
1406  *
1407  *         (C) is the point where Cancellation call-back is invoked.
1408  *
1409  *         (D) is the transit state which means the lock is changing.
1410  *
1411  *         Transition to FREEING state is possible from any other state in the
1412  *         diagram in case of unrecoverable error.
1413  * </pre>
1414  * \endhtmlonly
1415  *
1416  * These states are for individual cl_lock object. Top-lock and its sub-locks
1417  * can be in the different states. Another way to say this is that we have
1418  * nested state-machines.
1419  *
1420  * Separate QUEUING and ENQUEUED states are needed to support non-blocking
1421  * operation for locks with multiple sub-locks. Imagine lock on a file F, that
1422  * intersects 3 stripes S0, S1, and S2. To enqueue F client has to send
1423  * enqueue to S0, wait for its completion, then send enqueue for S1, wait for
1424  * its completion and at last enqueue lock for S2, and wait for its
1425  * completion. In that case, top-lock is in QUEUING state while S0, S1 are
1426  * handled, and is in ENQUEUED state after enqueue to S2 has been sent (note
1427  * that in this case, sub-locks move from state to state, and top-lock remains
1428  * in the same state).
1429  */
1430 enum cl_lock_state {
1431         /**
1432          * Lock that wasn't yet enqueued
1433          */
1434         CLS_NEW,
1435         /**
1436          * Enqueue is in progress, blocking for some intermediate interaction
1437          * with the other side.
1438          */
1439         CLS_QUEUING,
1440         /**
1441          * Lock is fully enqueued, waiting for server to reply when it is
1442          * granted.
1443          */
1444         CLS_ENQUEUED,
1445         /**
1446          * Lock granted, actively used by some IO.
1447          */
1448         CLS_HELD,
1449         /**
1450          * This state is used to mark the lock is being used, or unused.
1451          * We need this state because the lock may have several sublocks,
1452          * so it's impossible to have an atomic way to bring all sublocks
1453          * into CLS_HELD state at use case, or all sublocks to CLS_CACHED
1454          * at unuse case.
1455          * If a thread is referring to a lock, and it sees the lock is in this
1456          * state, it must wait for the lock.
1457          * See state diagram for details.
1458          */
1459         CLS_INTRANSIT,
1460         /**
1461          * Lock granted, not used.
1462          */
1463         CLS_CACHED,
1464         /**
1465          * Lock is being destroyed.
1466          */
1467         CLS_FREEING,
1468         CLS_NR
1469 };
1470
1471 enum cl_lock_flags {
1472         /**
1473          * lock has been cancelled. This flag is never cleared once set (by
1474          * cl_lock_cancel0()).
1475          */
1476         CLF_CANCELLED  = 1 << 0,
1477         /** cancellation is pending for this lock. */
1478         CLF_CANCELPEND = 1 << 1,
1479         /** destruction is pending for this lock. */
1480         CLF_DOOMED     = 1 << 2,
1481         /** from enqueue RPC reply upcall. */
1482         CLF_FROM_UPCALL= 1 << 3,
1483 };
1484
1485 /**
1486  * Lock closure.
1487  *
1488  * Lock closure is a collection of locks (both top-locks and sub-locks) that
1489  * might be updated in a result of an operation on a certain lock (which lock
1490  * this is a closure of).
1491  *
1492  * Closures are needed to guarantee dead-lock freedom in the presence of
1493  *
1494  *     - nested state-machines (top-lock state-machine composed of sub-lock
1495  *       state-machines), and
1496  *
1497  *     - shared sub-locks.
1498  *
1499  * Specifically, many operations, such as lock enqueue, wait, unlock,
1500  * etc. start from a top-lock, and then operate on a sub-locks of this
1501  * top-lock, holding a top-lock mutex. When sub-lock state changes as a result
1502  * of such operation, this change has to be propagated to all top-locks that
1503  * share this sub-lock. Obviously, no natural lock ordering (e.g.,
1504  * top-to-bottom or bottom-to-top) captures this scenario, so try-locking has
1505  * to be used. Lock closure systematizes this try-and-repeat logic.
1506  */
1507 struct cl_lock_closure {
1508         /**
1509          * Lock that is mutexed when closure construction is started. When
1510          * closure in is `wait' mode (cl_lock_closure::clc_wait), mutex on
1511          * origin is released before waiting.
1512          */
1513         struct cl_lock   *clc_origin;
1514         /**
1515          * List of enclosed locks, so far. Locks are linked here through
1516          * cl_lock::cll_inclosure.
1517          */
1518         cfs_list_t        clc_list;
1519         /**
1520          * True iff closure is in a `wait' mode. This determines what
1521          * cl_lock_enclosure() does when a lock L to be added to the closure
1522          * is currently mutexed by some other thread.
1523          *
1524          * If cl_lock_closure::clc_wait is not set, then closure construction
1525          * fails with CLO_REPEAT immediately.
1526          *
1527          * In wait mode, cl_lock_enclosure() waits until next attempt to build
1528          * a closure might succeed. To this end it releases an origin mutex
1529          * (cl_lock_closure::clc_origin), that has to be the only lock mutex
1530          * owned by the current thread, and then waits on L mutex (by grabbing
1531          * it and immediately releasing), before returning CLO_REPEAT to the
1532          * caller.
1533          */
1534         int               clc_wait;
1535         /** Number of locks in the closure. */
1536         int               clc_nr;
1537 };
1538
1539 /**
1540  * Layered client lock.
1541  */
1542 struct cl_lock {
1543         /** Reference counter. */
1544         cfs_atomic_t          cll_ref;
1545         /** List of slices. Immutable after creation. */
1546         cfs_list_t            cll_layers;
1547         /**
1548          * Linkage into cl_lock::cll_descr::cld_obj::coh_locks list. Protected
1549          * by cl_lock::cll_descr::cld_obj::coh_lock_guard.
1550          */
1551         cfs_list_t            cll_linkage;
1552         /**
1553          * Parameters of this lock. Protected by
1554          * cl_lock::cll_descr::cld_obj::coh_lock_guard nested within
1555          * cl_lock::cll_guard. Modified only on lock creation and in
1556          * cl_lock_modify().
1557          */
1558         struct cl_lock_descr  cll_descr;
1559         /** Protected by cl_lock::cll_guard. */
1560         enum cl_lock_state    cll_state;
1561         /** signals state changes. */
1562         cfs_waitq_t           cll_wq;
1563         /**
1564          * Recursive lock, most fields in cl_lock{} are protected by this.
1565          *
1566          * Locking rules: this mutex is never held across network
1567          * communication, except when lock is being canceled.
1568          *
1569          * Lock ordering: a mutex of a sub-lock is taken first, then a mutex
1570          * on a top-lock. Other direction is implemented through a
1571          * try-lock-repeat loop. Mutices of unrelated locks can be taken only
1572          * by try-locking.
1573          *
1574          * \see osc_lock_enqueue_wait(), lov_lock_cancel(), lov_sublock_wait().
1575          */
1576         struct mutex            cll_guard;
1577         cfs_task_t           *cll_guarder;
1578         int                   cll_depth;
1579
1580         /**
1581          * the owner for INTRANSIT state
1582          */
1583         cfs_task_t           *cll_intransit_owner;
1584         int                   cll_error;
1585         /**
1586          * Number of holds on a lock. A hold prevents a lock from being
1587          * canceled and destroyed. Protected by cl_lock::cll_guard.
1588          *
1589          * \see cl_lock_hold(), cl_lock_unhold(), cl_lock_release()
1590          */
1591         int                   cll_holds;
1592          /**
1593           * Number of lock users. Valid in cl_lock_state::CLS_HELD state
1594           * only. Lock user pins lock in CLS_HELD state. Protected by
1595           * cl_lock::cll_guard.
1596           *
1597           * \see cl_wait(), cl_unuse().
1598           */
1599         int                   cll_users;
1600         /**
1601          * Flag bit-mask. Values from enum cl_lock_flags. Updates are
1602          * protected by cl_lock::cll_guard.
1603          */
1604         unsigned long         cll_flags;
1605         /**
1606          * A linkage into a list of locks in a closure.
1607          *
1608          * \see cl_lock_closure
1609          */
1610         cfs_list_t            cll_inclosure;
1611         /**
1612          * Confict lock at queuing time.
1613          */
1614         struct cl_lock       *cll_conflict;
1615         /**
1616          * A list of references to this lock, for debugging.
1617          */
1618         struct lu_ref         cll_reference;
1619         /**
1620          * A list of holds on this lock, for debugging.
1621          */
1622         struct lu_ref         cll_holders;
1623         /**
1624          * A reference for cl_lock::cll_descr::cld_obj. For debugging.
1625          */
1626         struct lu_ref_link   *cll_obj_ref;
1627 #ifdef CONFIG_LOCKDEP
1628         /* "dep_map" name is assumed by lockdep.h macros. */
1629         struct lockdep_map    dep_map;
1630 #endif
1631 };
1632
1633 /**
1634  * Per-layer part of cl_lock
1635  *
1636  * \see ccc_lock, lov_lock, lovsub_lock, osc_lock
1637  */
1638 struct cl_lock_slice {
1639         struct cl_lock                  *cls_lock;
1640         /** Object slice corresponding to this lock slice. Immutable after
1641          * creation. */
1642         struct cl_object                *cls_obj;
1643         const struct cl_lock_operations *cls_ops;
1644         /** Linkage into cl_lock::cll_layers. Immutable after creation. */
1645         cfs_list_t                       cls_linkage;
1646 };
1647
1648 /**
1649  * Possible (non-error) return values of ->clo_{enqueue,wait,unlock}().
1650  *
1651  * NOTE: lov_subresult() depends on ordering here.
1652  */
1653 enum cl_lock_transition {
1654         /** operation cannot be completed immediately. Wait for state change. */
1655         CLO_WAIT        = 1,
1656         /** operation had to release lock mutex, restart. */
1657         CLO_REPEAT      = 2,
1658         /** lower layer re-enqueued. */
1659         CLO_REENQUEUED  = 3,
1660 };
1661
1662 /**
1663  *
1664  * \see vvp_lock_ops, lov_lock_ops, lovsub_lock_ops, osc_lock_ops
1665  */
1666 struct cl_lock_operations {
1667         /**
1668          * \name statemachine
1669          *
1670          * State machine transitions. These 3 methods are called to transfer
1671          * lock from one state to another, as described in the commentary
1672          * above enum #cl_lock_state.
1673          *
1674          * \retval 0          this layer has nothing more to do to before
1675          *                       transition to the target state happens;
1676          *
1677          * \retval CLO_REPEAT method had to release and re-acquire cl_lock
1678          *                    mutex, repeat invocation of transition method
1679          *                    across all layers;
1680          *
1681          * \retval CLO_WAIT   this layer cannot move to the target state
1682          *                    immediately, as it has to wait for certain event
1683          *                    (e.g., the communication with the server). It
1684          *                    is guaranteed, that when the state transfer
1685          *                    becomes possible, cl_lock::cll_wq wait-queue
1686          *                    is signaled. Caller can wait for this event by
1687          *                    calling cl_lock_state_wait();
1688          *
1689          * \retval -ve        failure, abort state transition, move the lock
1690          *                    into cl_lock_state::CLS_FREEING state, and set
1691          *                    cl_lock::cll_error.
1692          *
1693          * Once all layers voted to agree to transition (by returning 0), lock
1694          * is moved into corresponding target state. All state transition
1695          * methods are optional.
1696          */
1697         /** @{ */
1698         /**
1699          * Attempts to enqueue the lock. Called top-to-bottom.
1700          *
1701          * \see ccc_lock_enqueue(), lov_lock_enqueue(), lovsub_lock_enqueue(),
1702          * \see osc_lock_enqueue()
1703          */
1704         int  (*clo_enqueue)(const struct lu_env *env,
1705                             const struct cl_lock_slice *slice,
1706                             struct cl_io *io, __u32 enqflags);
1707         /**
1708          * Attempts to wait for enqueue result. Called top-to-bottom.
1709          *
1710          * \see ccc_lock_wait(), lov_lock_wait(), osc_lock_wait()
1711          */
1712         int  (*clo_wait)(const struct lu_env *env,
1713                          const struct cl_lock_slice *slice);
1714         /**
1715          * Attempts to unlock the lock. Called bottom-to-top. In addition to
1716          * usual return values of lock state-machine methods, this can return
1717          * -ESTALE to indicate that lock cannot be returned to the cache, and
1718          * has to be re-initialized.
1719          * unuse is a one-shot operation, so it must NOT return CLO_WAIT.
1720          *
1721          * \see ccc_lock_unuse(), lov_lock_unuse(), osc_lock_unuse()
1722          */
1723         int  (*clo_unuse)(const struct lu_env *env,
1724                           const struct cl_lock_slice *slice);
1725         /**
1726          * Notifies layer that cached lock is started being used.
1727          *
1728          * \pre lock->cll_state == CLS_CACHED
1729          *
1730          * \see lov_lock_use(), osc_lock_use()
1731          */
1732         int  (*clo_use)(const struct lu_env *env,
1733                         const struct cl_lock_slice *slice);
1734         /** @} statemachine */
1735         /**
1736          * A method invoked when lock state is changed (as a result of state
1737          * transition). This is used, for example, to track when the state of
1738          * a sub-lock changes, to propagate this change to the corresponding
1739          * top-lock. Optional
1740          *
1741          * \see lovsub_lock_state()
1742          */
1743         void (*clo_state)(const struct lu_env *env,
1744                           const struct cl_lock_slice *slice,
1745                           enum cl_lock_state st);
1746         /**
1747          * Returns true, iff given lock is suitable for the given io, idea
1748          * being, that there are certain "unsafe" locks, e.g., ones acquired
1749          * for O_APPEND writes, that we don't want to re-use for a normal
1750          * write, to avoid the danger of cascading evictions. Optional. Runs
1751          * under cl_object_header::coh_lock_guard.
1752          *
1753          * XXX this should take more information about lock needed by
1754          * io. Probably lock description or something similar.
1755          *
1756          * \see lov_fits_into()
1757          */
1758         int (*clo_fits_into)(const struct lu_env *env,
1759                              const struct cl_lock_slice *slice,
1760                              const struct cl_lock_descr *need,
1761                              const struct cl_io *io);
1762         /**
1763          * \name ast
1764          * Asynchronous System Traps. All of then are optional, all are
1765          * executed bottom-to-top.
1766          */
1767         /** @{ */
1768
1769         /**
1770          * Cancellation callback. Cancel a lock voluntarily, or under
1771          * the request of server.
1772          */
1773         void (*clo_cancel)(const struct lu_env *env,
1774                            const struct cl_lock_slice *slice);
1775         /**
1776          * Lock weighting ast. Executed to estimate how precious this lock
1777          * is. The sum of results across all layers is used to determine
1778          * whether lock worth keeping in cache given present memory usage.
1779          *
1780          * \see osc_lock_weigh(), vvp_lock_weigh(), lovsub_lock_weigh().
1781          */
1782         unsigned long (*clo_weigh)(const struct lu_env *env,
1783                                    const struct cl_lock_slice *slice);
1784         /** @} ast */
1785
1786         /**
1787          * \see lovsub_lock_closure()
1788          */
1789         int (*clo_closure)(const struct lu_env *env,
1790                            const struct cl_lock_slice *slice,
1791                            struct cl_lock_closure *closure);
1792         /**
1793          * Executed bottom-to-top when lock description changes (e.g., as a
1794          * result of server granting more generous lock than was requested).
1795          *
1796          * \see lovsub_lock_modify()
1797          */
1798         int (*clo_modify)(const struct lu_env *env,
1799                           const struct cl_lock_slice *slice,
1800                           const struct cl_lock_descr *updated);
1801         /**
1802          * Notifies layers (bottom-to-top) that lock is going to be
1803          * destroyed. Responsibility of layers is to prevent new references on
1804          * this lock from being acquired once this method returns.
1805          *
1806          * This can be called multiple times due to the races.
1807          *
1808          * \see cl_lock_delete()
1809          * \see osc_lock_delete(), lovsub_lock_delete()
1810          */
1811         void (*clo_delete)(const struct lu_env *env,
1812                            const struct cl_lock_slice *slice);
1813         /**
1814          * Destructor. Frees resources and the slice.
1815          *
1816          * \see ccc_lock_fini(), lov_lock_fini(), lovsub_lock_fini(),
1817          * \see osc_lock_fini()
1818          */
1819         void (*clo_fini)(const struct lu_env *env, struct cl_lock_slice *slice);
1820         /**
1821          * Optional debugging helper. Prints given lock slice.
1822          */
1823         int (*clo_print)(const struct lu_env *env,
1824                          void *cookie, lu_printer_t p,
1825                          const struct cl_lock_slice *slice);
1826 };
1827
1828 #define CL_LOCK_DEBUG(mask, env, lock, format, ...)                     \
1829 do {                                                                    \
1830         LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, mask, NULL);                \
1831                                                                         \
1832         if (cfs_cdebug_show(mask, DEBUG_SUBSYSTEM)) {                   \
1833                 cl_lock_print(env, &msgdata, lu_cdebug_printer, lock);  \
1834                 CDEBUG(mask, format , ## __VA_ARGS__);                  \
1835         }                                                               \
1836 } while (0)
1837
1838 #define CL_LOCK_ASSERT(expr, env, lock) do {                            \
1839         if (likely(expr))                                               \
1840                 break;                                                  \
1841                                                                         \
1842         CL_LOCK_DEBUG(D_ERROR, env, lock, "failed at %s.\n", #expr);    \
1843         LBUG();                                                         \
1844 } while (0)
1845
1846 /** @} cl_lock */
1847
1848 /** \addtogroup cl_page_list cl_page_list
1849  * Page list used to perform collective operations on a group of pages.
1850  *
1851  * Pages are added to the list one by one. cl_page_list acquires a reference
1852  * for every page in it. Page list is used to perform collective operations on
1853  * pages:
1854  *
1855  *     - submit pages for an immediate transfer,
1856  *
1857  *     - own pages on behalf of certain io (waiting for each page in turn),
1858  *
1859  *     - discard pages.
1860  *
1861  * When list is finalized, it releases references on all pages it still has.
1862  *
1863  * \todo XXX concurrency control.
1864  *
1865  * @{
1866  */
1867 struct cl_page_list {
1868         unsigned             pl_nr;
1869         cfs_list_t           pl_pages;
1870         cfs_task_t          *pl_owner;
1871 };
1872
1873 /** 
1874  * A 2-queue of pages. A convenience data-type for common use case, 2-queue
1875  * contains an incoming page list and an outgoing page list.
1876  */
1877 struct cl_2queue {
1878         struct cl_page_list c2_qin;
1879         struct cl_page_list c2_qout;
1880 };
1881
1882 /** @} cl_page_list */
1883
1884 /** \addtogroup cl_io cl_io
1885  * @{ */
1886 /** \struct cl_io
1887  * I/O
1888  *
1889  * cl_io represents a high level I/O activity like
1890  * read(2)/write(2)/truncate(2) system call, or cancellation of an extent
1891  * lock.
1892  *
1893  * cl_io is a layered object, much like cl_{object,page,lock} but with one
1894  * important distinction. We want to minimize number of calls to the allocator
1895  * in the fast path, e.g., in the case of read(2) when everything is cached:
1896  * client already owns the lock over region being read, and data are cached
1897  * due to read-ahead. To avoid allocation of cl_io layers in such situations,
1898  * per-layer io state is stored in the session, associated with the io, see
1899  * struct {vvp,lov,osc}_io for example. Sessions allocation is amortized
1900  * by using free-lists, see cl_env_get().
1901  *
1902  * There is a small predefined number of possible io types, enumerated in enum
1903  * cl_io_type.
1904  *
1905  * cl_io is a state machine, that can be advanced concurrently by the multiple
1906  * threads. It is up to these threads to control the concurrency and,
1907  * specifically, to detect when io is done, and its state can be safely
1908  * released.
1909  *
1910  * For read/write io overall execution plan is as following:
1911  *
1912  *     (0) initialize io state through all layers;
1913  *
1914  *     (1) loop: prepare chunk of work to do
1915  *
1916  *     (2) call all layers to collect locks they need to process current chunk
1917  *
1918  *     (3) sort all locks to avoid dead-locks, and acquire them
1919  *
1920  *     (4) process the chunk: call per-page methods
1921  *         (cl_io_operations::cio_read_page() for read,
1922  *         cl_io_operations::cio_prepare_write(),
1923  *         cl_io_operations::cio_commit_write() for write)
1924  *
1925  *     (5) release locks
1926  *
1927  *     (6) repeat loop.
1928  *
1929  * To implement the "parallel IO mode", lov layer creates sub-io's (lazily to
1930  * address allocation efficiency issues mentioned above), and returns with the
1931  * special error condition from per-page method when current sub-io has to
1932  * block. This causes io loop to be repeated, and lov switches to the next
1933  * sub-io in its cl_io_operations::cio_iter_init() implementation.
1934  */
1935
1936 /** IO types */
1937 enum cl_io_type {
1938         /** read system call */
1939         CIT_READ,
1940         /** write system call */
1941         CIT_WRITE,
1942         /** truncate, utime system calls */
1943         CIT_SETATTR,
1944         /**
1945          * page fault handling
1946          */
1947         CIT_FAULT,
1948         /**
1949          * fsync system call handling
1950          * To write out a range of file
1951          */
1952         CIT_FSYNC,
1953         /**
1954          * Miscellaneous io. This is used for occasional io activity that
1955          * doesn't fit into other types. Currently this is used for:
1956          *
1957          *     - cancellation of an extent lock. This io exists as a context
1958          *     to write dirty pages from under the lock being canceled back
1959          *     to the server;
1960          *
1961          *     - VM induced page write-out. An io context for writing page out
1962          *     for memory cleansing;
1963          *
1964          *     - glimpse. An io context to acquire glimpse lock.
1965          *
1966          *     - grouplock. An io context to acquire group lock.
1967          *
1968          * CIT_MISC io is used simply as a context in which locks and pages
1969          * are manipulated. Such io has no internal "process", that is,
1970          * cl_io_loop() is never called for it.
1971          */
1972         CIT_MISC,
1973         CIT_OP_NR
1974 };
1975
1976 /**
1977  * States of cl_io state machine
1978  */
1979 enum cl_io_state {
1980         /** Not initialized. */
1981         CIS_ZERO,
1982         /** Initialized. */
1983         CIS_INIT,
1984         /** IO iteration started. */
1985         CIS_IT_STARTED,
1986         /** Locks taken. */
1987         CIS_LOCKED,
1988         /** Actual IO is in progress. */
1989         CIS_IO_GOING,
1990         /** IO for the current iteration finished. */
1991         CIS_IO_FINISHED,
1992         /** Locks released. */
1993         CIS_UNLOCKED,
1994         /** Iteration completed. */
1995         CIS_IT_ENDED,
1996         /** cl_io finalized. */
1997         CIS_FINI
1998 };
1999
2000 /**
2001  * IO state private for a layer.
2002  *
2003  * This is usually embedded into layer session data, rather than allocated
2004  * dynamically.
2005  *
2006  * \see vvp_io, lov_io, osc_io, ccc_io
2007  */
2008 struct cl_io_slice {
2009         struct cl_io                  *cis_io;
2010         /** corresponding object slice. Immutable after creation. */
2011         struct cl_object              *cis_obj;
2012         /** io operations. Immutable after creation. */
2013         const struct cl_io_operations *cis_iop;
2014         /**
2015          * linkage into a list of all slices for a given cl_io, hanging off
2016          * cl_io::ci_layers. Immutable after creation.
2017          */
2018         cfs_list_t                     cis_linkage;
2019 };
2020
2021
2022 /**
2023  * Per-layer io operations.
2024  * \see vvp_io_ops, lov_io_ops, lovsub_io_ops, osc_io_ops
2025  */
2026 struct cl_io_operations {
2027         /**
2028          * Vector of io state transition methods for every io type.
2029          *
2030          * \see cl_page_operations::io
2031          */
2032         struct {
2033                 /**
2034                  * Prepare io iteration at a given layer.
2035                  *
2036                  * Called top-to-bottom at the beginning of each iteration of
2037                  * "io loop" (if it makes sense for this type of io). Here
2038                  * layer selects what work it will do during this iteration.
2039                  *
2040                  * \see cl_io_operations::cio_iter_fini()
2041                  */
2042                 int (*cio_iter_init) (const struct lu_env *env,
2043                                       const struct cl_io_slice *slice);
2044                 /**
2045                  * Finalize io iteration.
2046                  *
2047                  * Called bottom-to-top at the end of each iteration of "io
2048                  * loop". Here layers can decide whether IO has to be
2049                  * continued.
2050                  *
2051                  * \see cl_io_operations::cio_iter_init()
2052                  */
2053                 void (*cio_iter_fini) (const struct lu_env *env,
2054                                        const struct cl_io_slice *slice);
2055                 /**
2056                  * Collect locks for the current iteration of io.
2057                  *
2058                  * Called top-to-bottom to collect all locks necessary for
2059                  * this iteration. This methods shouldn't actually enqueue
2060                  * anything, instead it should post a lock through
2061                  * cl_io_lock_add(). Once all locks are collected, they are
2062                  * sorted and enqueued in the proper order.
2063                  */
2064                 int  (*cio_lock) (const struct lu_env *env,
2065                                   const struct cl_io_slice *slice);
2066                 /**
2067                  * Finalize unlocking.
2068                  *
2069                  * Called bottom-to-top to finish layer specific unlocking
2070                  * functionality, after generic code released all locks
2071                  * acquired by cl_io_operations::cio_lock().
2072                  */
2073                 void  (*cio_unlock)(const struct lu_env *env,
2074                                     const struct cl_io_slice *slice);
2075                 /**
2076                  * Start io iteration.
2077                  *
2078                  * Once all locks are acquired, called top-to-bottom to
2079                  * commence actual IO. In the current implementation,
2080                  * top-level vvp_io_{read,write}_start() does all the work
2081                  * synchronously by calling generic_file_*(), so other layers
2082                  * are called when everything is done.
2083                  */
2084                 int  (*cio_start)(const struct lu_env *env,
2085                                   const struct cl_io_slice *slice);
2086                 /**
2087                  * Called top-to-bottom at the end of io loop. Here layer
2088                  * might wait for an unfinished asynchronous io.
2089                  */
2090                 void (*cio_end)  (const struct lu_env *env,
2091                                   const struct cl_io_slice *slice);
2092                 /**
2093                  * Called bottom-to-top to notify layers that read/write IO
2094                  * iteration finished, with \a nob bytes transferred.
2095                  */
2096                 void (*cio_advance)(const struct lu_env *env,
2097                                     const struct cl_io_slice *slice,
2098                                     size_t nob);
2099                 /**
2100                  * Called once per io, bottom-to-top to release io resources.
2101                  */
2102                 void (*cio_fini) (const struct lu_env *env,
2103                                   const struct cl_io_slice *slice);
2104         } op[CIT_OP_NR];
2105         struct {
2106                 /**
2107                  * Submit pages from \a queue->c2_qin for IO, and move
2108                  * successfully submitted pages into \a queue->c2_qout. Return
2109                  * non-zero if failed to submit even the single page. If
2110                  * submission failed after some pages were moved into \a
2111                  * queue->c2_qout, completion callback with non-zero ioret is
2112                  * executed on them.
2113                  */
2114                 int  (*cio_submit)(const struct lu_env *env,
2115                                    const struct cl_io_slice *slice,
2116                                    enum cl_req_type crt,
2117                                    struct cl_2queue *queue);
2118         } req_op[CRT_NR];
2119         /**
2120          * Read missing page.
2121          *
2122          * Called by a top-level cl_io_operations::op[CIT_READ]::cio_start()
2123          * method, when it hits not-up-to-date page in the range. Optional.
2124          *
2125          * \pre io->ci_type == CIT_READ
2126          */
2127         int (*cio_read_page)(const struct lu_env *env,
2128                              const struct cl_io_slice *slice,
2129                              const struct cl_page_slice *page);
2130         /**
2131          * Prepare write of a \a page. Called bottom-to-top by a top-level
2132          * cl_io_operations::op[CIT_WRITE]::cio_start() to prepare page for
2133          * get data from user-level buffer.
2134          *
2135          * \pre io->ci_type == CIT_WRITE
2136          *
2137          * \see vvp_io_prepare_write(), lov_io_prepare_write(),
2138          * osc_io_prepare_write().
2139          */
2140         int (*cio_prepare_write)(const struct lu_env *env,
2141                                  const struct cl_io_slice *slice,
2142                                  const struct cl_page_slice *page,
2143                                  unsigned from, unsigned to);
2144         /**
2145          *
2146          * \pre io->ci_type == CIT_WRITE
2147          *
2148          * \see vvp_io_commit_write(), lov_io_commit_write(),
2149          * osc_io_commit_write().
2150          */
2151         int (*cio_commit_write)(const struct lu_env *env,
2152                                 const struct cl_io_slice *slice,
2153                                 const struct cl_page_slice *page,
2154                                 unsigned from, unsigned to);
2155         /**
2156          * Optional debugging helper. Print given io slice.
2157          */
2158         int (*cio_print)(const struct lu_env *env, void *cookie,
2159                          lu_printer_t p, const struct cl_io_slice *slice);
2160 };
2161
2162 /**
2163  * Flags to lock enqueue procedure.
2164  * \ingroup cl_lock
2165  */
2166 enum cl_enq_flags {
2167         /**
2168          * instruct server to not block, if conflicting lock is found. Instead
2169          * -EWOULDBLOCK is returned immediately.
2170          */
2171         CEF_NONBLOCK     = 0x00000001,
2172         /**
2173          * take lock asynchronously (out of order), as it cannot
2174          * deadlock. This is for LDLM_FL_HAS_INTENT locks used for glimpsing.
2175          */
2176         CEF_ASYNC        = 0x00000002,
2177         /**
2178          * tell the server to instruct (though a flag in the blocking ast) an
2179          * owner of the conflicting lock, that it can drop dirty pages
2180          * protected by this lock, without sending them to the server.
2181          */
2182         CEF_DISCARD_DATA = 0x00000004,
2183         /**
2184          * tell the sub layers that it must be a `real' lock. This is used for
2185          * mmapped-buffer locks and glimpse locks that must be never converted
2186          * into lockless mode.
2187          *
2188          * \see vvp_mmap_locks(), cl_glimpse_lock().
2189          */
2190         CEF_MUST         = 0x00000008,
2191         /**
2192          * tell the sub layers that never request a `real' lock. This flag is
2193          * not used currently.
2194          *
2195          * cl_io::ci_lockreq and CEF_{MUST,NEVER} flags specify lockless
2196          * conversion policy: ci_lockreq describes generic information of lock
2197          * requirement for this IO, especially for locks which belong to the
2198          * object doing IO; however, lock itself may have precise requirements
2199          * that are described by the enqueue flags.
2200          */
2201         CEF_NEVER        = 0x00000010,
2202         /**
2203          * for async glimpse lock.
2204          */
2205         CEF_AGL          = 0x00000020,
2206         /**
2207          * mask of enq_flags.
2208          */
2209         CEF_MASK         = 0x0000003f,
2210 };
2211
2212 /**
2213  * Link between lock and io. Intermediate structure is needed, because the
2214  * same lock can be part of multiple io's simultaneously.
2215  */
2216 struct cl_io_lock_link {
2217         /** linkage into one of cl_lockset lists. */
2218         cfs_list_t           cill_linkage;
2219         struct cl_lock_descr cill_descr;
2220         struct cl_lock      *cill_lock;
2221         /** optional destructor */
2222         void               (*cill_fini)(const struct lu_env *env,
2223                                         struct cl_io_lock_link *link);
2224 };
2225
2226 /**
2227  * Lock-set represents a collection of locks, that io needs at a
2228  * time. Generally speaking, client tries to avoid holding multiple locks when
2229  * possible, because
2230  *
2231  *      - holding extent locks over multiple ost's introduces the danger of
2232  *        "cascading timeouts";
2233  *
2234  *      - holding multiple locks over the same ost is still dead-lock prone,
2235  *        see comment in osc_lock_enqueue(),
2236  *
2237  * but there are certain situations where this is unavoidable:
2238  *
2239  *      - O_APPEND writes have to take [0, EOF] lock for correctness;
2240  *
2241  *      - truncate has to take [new-size, EOF] lock for correctness;
2242  *
2243  *      - SNS has to take locks across full stripe for correctness;
2244  *
2245  *      - in the case when user level buffer, supplied to {read,write}(file0),
2246  *        is a part of a memory mapped lustre file, client has to take a dlm
2247  *        locks on file0, and all files that back up the buffer (or a part of
2248  *        the buffer, that is being processed in the current chunk, in any
2249  *        case, there are situations where at least 2 locks are necessary).
2250  *
2251  * In such cases we at least try to take locks in the same consistent
2252  * order. To this end, all locks are first collected, then sorted, and then
2253  * enqueued.
2254  */
2255 struct cl_lockset {
2256         /** locks to be acquired. */
2257         cfs_list_t  cls_todo;
2258         /** locks currently being processed. */
2259         cfs_list_t  cls_curr;
2260         /** locks acquired. */
2261         cfs_list_t  cls_done;
2262 };
2263
2264 /**
2265  * Lock requirements(demand) for IO. It should be cl_io_lock_req,
2266  * but 'req' is always to be thought as 'request' :-)
2267  */
2268 enum cl_io_lock_dmd {
2269         /** Always lock data (e.g., O_APPEND). */
2270         CILR_MANDATORY = 0,
2271         /** Layers are free to decide between local and global locking. */
2272         CILR_MAYBE,
2273         /** Never lock: there is no cache (e.g., liblustre). */
2274         CILR_NEVER,
2275         /** Peek lock: use existing locks, don't queue new ones */
2276         CILR_PEEK
2277 };
2278
2279 enum cl_fsync_mode {
2280         /** start writeback, do not wait for them to finish */
2281         CL_FSYNC_NONE  = 0,
2282         /** start writeback and wait for them to finish */
2283         CL_FSYNC_LOCAL = 1,
2284         /** discard all of dirty pages in a specific file range */
2285         CL_FSYNC_DISCARD = 2,
2286         /** start writeback and make sure they have reached storage before
2287          * return. OST_SYNC RPC must be issued and finished */
2288         CL_FSYNC_ALL   = 3
2289 };
2290
2291 struct cl_io_rw_common {
2292         loff_t      crw_pos;
2293         size_t      crw_count;
2294         int         crw_nonblock;
2295 };
2296
2297
2298 /**
2299  * State for io.
2300  *
2301  * cl_io is shared by all threads participating in this IO (in current
2302  * implementation only one thread advances IO, but parallel IO design and
2303  * concurrent copy_*_user() require multiple threads acting on the same IO. It
2304  * is up to these threads to serialize their activities, including updates to
2305  * mutable cl_io fields.
2306  */
2307 struct cl_io {
2308         /** type of this IO. Immutable after creation. */
2309         enum cl_io_type                ci_type;
2310         /** current state of cl_io state machine. */
2311         enum cl_io_state               ci_state;
2312         /** main object this io is against. Immutable after creation. */
2313         struct cl_object              *ci_obj;
2314         /**
2315          * Upper layer io, of which this io is a part of. Immutable after
2316          * creation.
2317          */
2318         struct cl_io                  *ci_parent;
2319         /** List of slices. Immutable after creation. */
2320         cfs_list_t                     ci_layers;
2321         /** list of locks (to be) acquired by this io. */
2322         struct cl_lockset              ci_lockset;
2323         /** lock requirements, this is just a help info for sublayers. */
2324         enum cl_io_lock_dmd            ci_lockreq;
2325         union {
2326                 struct cl_rd_io {
2327                         struct cl_io_rw_common rd;
2328                 } ci_rd;
2329                 struct cl_wr_io {
2330                         struct cl_io_rw_common wr;
2331                         int                    wr_append;
2332                         int                    wr_sync;
2333                 } ci_wr;
2334                 struct cl_io_rw_common ci_rw;
2335                 struct cl_setattr_io {
2336                         struct ost_lvb   sa_attr;
2337                         unsigned int     sa_valid;
2338                         struct obd_capa *sa_capa;
2339                 } ci_setattr;
2340                 struct cl_fault_io {
2341                         /** page index within file. */
2342                         pgoff_t         ft_index;
2343                         /** bytes valid byte on a faulted page. */
2344                         int             ft_nob;
2345                         /** writable page? for nopage() only */
2346                         int             ft_writable;
2347                         /** page of an executable? */
2348                         int             ft_executable;
2349                         /** page_mkwrite() */
2350                         int             ft_mkwrite;
2351                         /** resulting page */
2352                         struct cl_page *ft_page;
2353                 } ci_fault;
2354                 struct cl_fsync_io {
2355                         loff_t             fi_start;
2356                         loff_t             fi_end;
2357                         struct obd_capa   *fi_capa;
2358                         /** file system level fid */
2359                         struct lu_fid     *fi_fid;
2360                         enum cl_fsync_mode fi_mode;
2361                         /* how many pages were written/discarded */
2362                         unsigned int       fi_nr_written;
2363                 } ci_fsync;
2364         } u;
2365         struct cl_2queue     ci_queue;
2366         size_t               ci_nob;
2367         int                  ci_result;
2368         unsigned int         ci_continue:1,
2369         /**
2370          * This io has held grouplock, to inform sublayers that
2371          * don't do lockless i/o.
2372          */
2373                              ci_no_srvlock:1,
2374         /**
2375          * The whole IO need to be restarted because layout has been changed
2376          */
2377                              ci_need_restart:1,
2378         /**
2379          * to not refresh layout - the IO issuer knows that the layout won't
2380          * change(page operations, layout change causes all page to be
2381          * discarded), or it doesn't matter if it changes(sync).
2382          */
2383                              ci_ignore_layout:1,
2384         /**
2385          * Check if layout changed after the IO finishes. Mainly for HSM
2386          * requirement. If IO occurs to openning files, it doesn't need to
2387          * verify layout because HSM won't release openning files.
2388          * Right now, only two opertaions need to verify layout: glimpse
2389          * and setattr.
2390          */
2391                              ci_verify_layout:1;
2392         /**
2393          * Number of pages owned by this IO. For invariant checking.
2394          */
2395         unsigned             ci_owned_nr;
2396 };
2397
2398 /** @} cl_io */
2399
2400 /** \addtogroup cl_req cl_req
2401  * @{ */
2402 /** \struct cl_req
2403  * Transfer.
2404  *
2405  * There are two possible modes of transfer initiation on the client:
2406  *
2407  *     - immediate transfer: this is started when a high level io wants a page
2408  *       or a collection of pages to be transferred right away. Examples:
2409  *       read-ahead, synchronous read in the case of non-page aligned write,
2410  *       page write-out as a part of extent lock cancellation, page write-out
2411  *       as a part of memory cleansing. Immediate transfer can be both
2412  *       cl_req_type::CRT_READ and cl_req_type::CRT_WRITE;
2413  *
2414  *     - opportunistic transfer (cl_req_type::CRT_WRITE only), that happens
2415  *       when io wants to transfer a page to the server some time later, when
2416  *       it can be done efficiently. Example: pages dirtied by the write(2)
2417  *       path.
2418  *
2419  * In any case, transfer takes place in the form of a cl_req, which is a
2420  * representation for a network RPC.
2421  *
2422  * Pages queued for an opportunistic transfer are cached until it is decided
2423  * that efficient RPC can be composed of them. This decision is made by "a
2424  * req-formation engine", currently implemented as a part of osc
2425  * layer. Req-formation depends on many factors: the size of the resulting
2426  * RPC, whether or not multi-object RPCs are supported by the server,
2427  * max-rpc-in-flight limitations, size of the dirty cache, etc.
2428  *
2429  * For the immediate transfer io submits a cl_page_list, that req-formation
2430  * engine slices into cl_req's, possibly adding cached pages to some of
2431  * the resulting req's.
2432  *
2433  * Whenever a page from cl_page_list is added to a newly constructed req, its
2434  * cl_page_operations::cpo_prep() layer methods are called. At that moment,
2435  * page state is atomically changed from cl_page_state::CPS_OWNED to
2436  * cl_page_state::CPS_PAGEOUT or cl_page_state::CPS_PAGEIN, cl_page::cp_owner
2437  * is zeroed, and cl_page::cp_req is set to the
2438  * req. cl_page_operations::cpo_prep() method at the particular layer might
2439  * return -EALREADY to indicate that it does not need to submit this page
2440  * at all. This is possible, for example, if page, submitted for read,
2441  * became up-to-date in the meantime; and for write, the page don't have
2442  * dirty bit marked. \see cl_io_submit_rw()
2443  *
2444  * Whenever a cached page is added to a newly constructed req, its
2445  * cl_page_operations::cpo_make_ready() layer methods are called. At that
2446  * moment, page state is atomically changed from cl_page_state::CPS_CACHED to
2447  * cl_page_state::CPS_PAGEOUT, and cl_page::cp_req is set to
2448  * req. cl_page_operations::cpo_make_ready() method at the particular layer
2449  * might return -EAGAIN to indicate that this page is not eligible for the
2450  * transfer right now.
2451  *
2452  * FUTURE
2453  *
2454  * Plan is to divide transfers into "priority bands" (indicated when
2455  * submitting cl_page_list, and queuing a page for the opportunistic transfer)
2456  * and allow glueing of cached pages to immediate transfers only within single
2457  * band. This would make high priority transfers (like lock cancellation or
2458  * memory pressure induced write-out) really high priority.
2459  *
2460  */
2461
2462 /**
2463  * Per-transfer attributes.
2464  */
2465 struct cl_req_attr {
2466         /** Generic attributes for the server consumption. */
2467         struct obdo     *cra_oa;
2468         /** Capability. */
2469         struct obd_capa *cra_capa;
2470         /** Jobid */
2471         char             cra_jobid[JOBSTATS_JOBID_SIZE];
2472 };
2473
2474 /**
2475  * Transfer request operations definable at every layer.
2476  *
2477  * Concurrency: transfer formation engine synchronizes calls to all transfer
2478  * methods.
2479  */
2480 struct cl_req_operations {
2481         /**
2482          * Invoked top-to-bottom by cl_req_prep() when transfer formation is
2483          * complete (all pages are added).
2484          *
2485          * \see osc_req_prep()
2486          */
2487         int  (*cro_prep)(const struct lu_env *env,
2488                          const struct cl_req_slice *slice);
2489         /**
2490          * Called top-to-bottom to fill in \a oa fields. This is called twice
2491          * with different flags, see bug 10150 and osc_build_req().
2492          *
2493          * \param obj an object from cl_req which attributes are to be set in
2494          *            \a oa.
2495          *
2496          * \param oa struct obdo where attributes are placed
2497          *
2498          * \param flags \a oa fields to be filled.
2499          */
2500         void (*cro_attr_set)(const struct lu_env *env,
2501                              const struct cl_req_slice *slice,
2502                              const struct cl_object *obj,
2503                              struct cl_req_attr *attr, obd_valid flags);
2504         /**
2505          * Called top-to-bottom from cl_req_completion() to notify layers that
2506          * transfer completed. Has to free all state allocated by
2507          * cl_device_operations::cdo_req_init().
2508          */
2509         void (*cro_completion)(const struct lu_env *env,
2510                                const struct cl_req_slice *slice, int ioret);
2511 };
2512
2513 /**
2514  * A per-object state that (potentially multi-object) transfer request keeps.
2515  */
2516 struct cl_req_obj {
2517         /** object itself */
2518         struct cl_object   *ro_obj;
2519         /** reference to cl_req_obj::ro_obj. For debugging. */
2520         struct lu_ref_link *ro_obj_ref;
2521         /* something else? Number of pages for a given object? */
2522 };
2523
2524 /**
2525  * Transfer request.
2526  *
2527  * Transfer requests are not reference counted, because IO sub-system owns
2528  * them exclusively and knows when to free them.
2529  *
2530  * Life cycle.
2531  *
2532  * cl_req is created by cl_req_alloc() that calls
2533  * cl_device_operations::cdo_req_init() device methods to allocate per-req
2534  * state in every layer.
2535  *
2536  * Then pages are added (cl_req_page_add()), req keeps track of all objects it
2537  * contains pages for.
2538  *
2539  * Once all pages were collected, cl_page_operations::cpo_prep() method is
2540  * called top-to-bottom. At that point layers can modify req, let it pass, or
2541  * deny it completely. This is to support things like SNS that have transfer
2542  * ordering requirements invisible to the individual req-formation engine.
2543  *
2544  * On transfer completion (or transfer timeout, or failure to initiate the
2545  * transfer of an allocated req), cl_req_operations::cro_completion() method
2546  * is called, after execution of cl_page_operations::cpo_completion() of all
2547  * req's pages.
2548  */
2549 struct cl_req {
2550         enum cl_req_type      crq_type;
2551         /** A list of pages being transfered */
2552         cfs_list_t            crq_pages;
2553         /** Number of pages in cl_req::crq_pages */
2554         unsigned              crq_nrpages;
2555         /** An array of objects which pages are in ->crq_pages */
2556         struct cl_req_obj    *crq_o;
2557         /** Number of elements in cl_req::crq_objs[] */
2558         unsigned              crq_nrobjs;
2559         cfs_list_t            crq_layers;
2560 };
2561
2562 /**
2563  * Per-layer state for request.
2564  */
2565 struct cl_req_slice {
2566         struct cl_req    *crs_req;
2567         struct cl_device *crs_dev;
2568         cfs_list_t        crs_linkage;
2569         const struct cl_req_operations *crs_ops;
2570 };
2571
2572 /* @} cl_req */
2573
2574 enum cache_stats_item {
2575         /** how many cache lookups were performed */
2576         CS_lookup = 0,
2577         /** how many times cache lookup resulted in a hit */
2578         CS_hit,
2579         /** how many entities are in the cache right now */
2580         CS_total,
2581         /** how many entities in the cache are actively used (and cannot be
2582          * evicted) right now */
2583         CS_busy,
2584         /** how many entities were created at all */
2585         CS_create,
2586         CS_NR
2587 };
2588
2589 #define CS_NAMES { "lookup", "hit", "total", "busy", "create" }
2590
2591 /**
2592  * Stats for a generic cache (similar to inode, lu_object, etc. caches).
2593  */
2594 struct cache_stats {
2595         const char    *cs_name;
2596         cfs_atomic_t   cs_stats[CS_NR];
2597 };
2598
2599 /** These are not exported so far */
2600 void cache_stats_init (struct cache_stats *cs, const char *name);
2601 int  cache_stats_print(const struct cache_stats *cs,
2602                        char *page, int count, int header);
2603
2604 /**
2605  * Client-side site. This represents particular client stack. "Global"
2606  * variables should (directly or indirectly) be added here to allow multiple
2607  * clients to co-exist in the single address space.
2608  */
2609 struct cl_site {
2610         struct lu_site        cs_lu;
2611         /**
2612          * Statistical counters. Atomics do not scale, something better like
2613          * per-cpu counters is needed.
2614          *
2615          * These are exported as /proc/fs/lustre/llite/.../site
2616          *
2617          * When interpreting keep in mind that both sub-locks (and sub-pages)
2618          * and top-locks (and top-pages) are accounted here.
2619          */
2620         struct cache_stats    cs_pages;
2621         struct cache_stats    cs_locks;
2622         cfs_atomic_t          cs_pages_state[CPS_NR];
2623         cfs_atomic_t          cs_locks_state[CLS_NR];
2624 };
2625
2626 int  cl_site_init (struct cl_site *s, struct cl_device *top);
2627 void cl_site_fini (struct cl_site *s);
2628 void cl_stack_fini(const struct lu_env *env, struct cl_device *cl);
2629
2630 /**
2631  * Output client site statistical counters into a buffer. Suitable for
2632  * ll_rd_*()-style functions.
2633  */
2634 int cl_site_stats_print(const struct cl_site *s, char *page, int count);
2635
2636 /**
2637  * \name helpers
2638  *
2639  * Type conversion and accessory functions.
2640  */
2641 /** @{ */
2642
2643 static inline struct cl_site *lu2cl_site(const struct lu_site *site)
2644 {
2645         return container_of(site, struct cl_site, cs_lu);
2646 }
2647
2648 static inline int lu_device_is_cl(const struct lu_device *d)
2649 {
2650         return d->ld_type->ldt_tags & LU_DEVICE_CL;
2651 }
2652
2653 static inline struct cl_device *lu2cl_dev(const struct lu_device *d)
2654 {
2655         LASSERT(d == NULL || IS_ERR(d) || lu_device_is_cl(d));
2656         return container_of0(d, struct cl_device, cd_lu_dev);
2657 }
2658
2659 static inline struct lu_device *cl2lu_dev(struct cl_device *d)
2660 {
2661         return &d->cd_lu_dev;
2662 }
2663
2664 static inline struct cl_object *lu2cl(const struct lu_object *o)
2665 {
2666         LASSERT(o == NULL || IS_ERR(o) || lu_device_is_cl(o->lo_dev));
2667         return container_of0(o, struct cl_object, co_lu);
2668 }
2669
2670 static inline const struct cl_object_conf *
2671 lu2cl_conf(const struct lu_object_conf *conf)
2672 {
2673         return container_of0(conf, struct cl_object_conf, coc_lu);
2674 }
2675
2676 static inline struct cl_object *cl_object_next(const struct cl_object *obj)
2677 {
2678         return obj ? lu2cl(lu_object_next(&obj->co_lu)) : NULL;
2679 }
2680
2681 static inline struct cl_device *cl_object_device(const struct cl_object *o)
2682 {
2683         LASSERT(o == NULL || IS_ERR(o) || lu_device_is_cl(o->co_lu.lo_dev));
2684         return container_of0(o->co_lu.lo_dev, struct cl_device, cd_lu_dev);
2685 }
2686
2687 static inline struct cl_object_header *luh2coh(const struct lu_object_header *h)
2688 {
2689         return container_of0(h, struct cl_object_header, coh_lu);
2690 }
2691
2692 static inline struct cl_site *cl_object_site(const struct cl_object *obj)
2693 {
2694         return lu2cl_site(obj->co_lu.lo_dev->ld_site);
2695 }
2696
2697 static inline
2698 struct cl_object_header *cl_object_header(const struct cl_object *obj)
2699 {
2700         return luh2coh(obj->co_lu.lo_header);
2701 }
2702
2703 static inline int cl_device_init(struct cl_device *d, struct lu_device_type *t)
2704 {
2705         return lu_device_init(&d->cd_lu_dev, t);
2706 }
2707
2708 static inline void cl_device_fini(struct cl_device *d)
2709 {
2710         lu_device_fini(&d->cd_lu_dev);
2711 }
2712
2713 void cl_page_slice_add(struct cl_page *page, struct cl_page_slice *slice,
2714                        struct cl_object *obj,
2715                        const struct cl_page_operations *ops);
2716 void cl_lock_slice_add(struct cl_lock *lock, struct cl_lock_slice *slice,
2717                        struct cl_object *obj,
2718                        const struct cl_lock_operations *ops);
2719 void cl_io_slice_add(struct cl_io *io, struct cl_io_slice *slice,
2720                      struct cl_object *obj, const struct cl_io_operations *ops);
2721 void cl_req_slice_add(struct cl_req *req, struct cl_req_slice *slice,
2722                       struct cl_device *dev,
2723                       const struct cl_req_operations *ops);
2724 /** @} helpers */
2725
2726 /** \defgroup cl_object cl_object
2727  * @{ */
2728 struct cl_object *cl_object_top (struct cl_object *o);
2729 struct cl_object *cl_object_find(const struct lu_env *env, struct cl_device *cd,
2730                                  const struct lu_fid *fid,
2731                                  const struct cl_object_conf *c);
2732
2733 int  cl_object_header_init(struct cl_object_header *h);
2734 void cl_object_header_fini(struct cl_object_header *h);
2735 void cl_object_put        (const struct lu_env *env, struct cl_object *o);
2736 void cl_object_get        (struct cl_object *o);
2737 void cl_object_attr_lock  (struct cl_object *o);
2738 void cl_object_attr_unlock(struct cl_object *o);
2739 int  cl_object_attr_get   (const struct lu_env *env, struct cl_object *obj,
2740                            struct cl_attr *attr);
2741 int  cl_object_attr_set   (const struct lu_env *env, struct cl_object *obj,
2742                            const struct cl_attr *attr, unsigned valid);
2743 int  cl_object_glimpse    (const struct lu_env *env, struct cl_object *obj,
2744                            struct ost_lvb *lvb);
2745 int  cl_conf_set          (const struct lu_env *env, struct cl_object *obj,
2746                            const struct cl_object_conf *conf);
2747 void cl_object_prune      (const struct lu_env *env, struct cl_object *obj);
2748 void cl_object_kill       (const struct lu_env *env, struct cl_object *obj);
2749 int  cl_object_has_locks  (struct cl_object *obj);
2750
2751 /**
2752  * Returns true, iff \a o0 and \a o1 are slices of the same object.
2753  */
2754 static inline int cl_object_same(struct cl_object *o0, struct cl_object *o1)
2755 {
2756         return cl_object_header(o0) == cl_object_header(o1);
2757 }
2758
2759 /** @} cl_object */
2760
2761 /** \defgroup cl_page cl_page
2762  * @{ */
2763 enum {
2764         CLP_GANG_OKAY = 0,
2765         CLP_GANG_RESCHED,
2766         CLP_GANG_AGAIN,
2767         CLP_GANG_ABORT
2768 };
2769
2770 /* callback of cl_page_gang_lookup() */
2771 typedef int   (*cl_page_gang_cb_t)  (const struct lu_env *, struct cl_io *,
2772                                      struct cl_page *, void *);
2773 int             cl_page_gang_lookup (const struct lu_env *env,
2774                                      struct cl_object *obj,
2775                                      struct cl_io *io,
2776                                      pgoff_t start, pgoff_t end,
2777                                      cl_page_gang_cb_t cb, void *cbdata);
2778 struct cl_page *cl_page_lookup      (struct cl_object_header *hdr,
2779                                      pgoff_t index);
2780 struct cl_page *cl_page_find        (const struct lu_env *env,
2781                                      struct cl_object *obj,
2782                                      pgoff_t idx, struct page *vmpage,
2783                                      enum cl_page_type type);
2784 struct cl_page *cl_page_find_sub    (const struct lu_env *env,
2785                                      struct cl_object *obj,
2786                                      pgoff_t idx, struct page *vmpage,
2787                                      struct cl_page *parent);
2788 void            cl_page_get         (struct cl_page *page);
2789 void            cl_page_put         (const struct lu_env *env,
2790                                      struct cl_page *page);
2791 void            cl_page_print       (const struct lu_env *env, void *cookie,
2792                                      lu_printer_t printer,
2793                                      const struct cl_page *pg);
2794 void            cl_page_header_print(const struct lu_env *env, void *cookie,
2795                                      lu_printer_t printer,
2796                                      const struct cl_page *pg);
2797 cfs_page_t     *cl_page_vmpage      (const struct lu_env *env,
2798                                      struct cl_page *page);
2799 struct cl_page *cl_vmpage_page      (cfs_page_t *vmpage, struct cl_object *obj);
2800 struct cl_page *cl_page_top         (struct cl_page *page);
2801
2802 const struct cl_page_slice *cl_page_at(const struct cl_page *page,
2803                                        const struct lu_device_type *dtype);
2804
2805 /**
2806  * \name ownership
2807  *
2808  * Functions dealing with the ownership of page by io.
2809  */
2810 /** @{ */
2811
2812 int  cl_page_own        (const struct lu_env *env,
2813                          struct cl_io *io, struct cl_page *page);
2814 int  cl_page_own_try    (const struct lu_env *env,
2815                          struct cl_io *io, struct cl_page *page);
2816 void cl_page_assume     (const struct lu_env *env,
2817                          struct cl_io *io, struct cl_page *page);
2818 void cl_page_unassume   (const struct lu_env *env,
2819                          struct cl_io *io, struct cl_page *pg);
2820 void cl_page_disown     (const struct lu_env *env,
2821                          struct cl_io *io, struct cl_page *page);
2822 int  cl_page_is_owned   (const struct cl_page *pg, const struct cl_io *io);
2823
2824 /** @} ownership */
2825
2826 /**
2827  * \name transfer
2828  *
2829  * Functions dealing with the preparation of a page for a transfer, and
2830  * tracking transfer state.
2831  */
2832 /** @{ */
2833 int  cl_page_prep       (const struct lu_env *env, struct cl_io *io,
2834                          struct cl_page *pg, enum cl_req_type crt);
2835 void cl_page_completion (const struct lu_env *env,
2836                          struct cl_page *pg, enum cl_req_type crt, int ioret);
2837 int  cl_page_make_ready (const struct lu_env *env, struct cl_page *pg,
2838                          enum cl_req_type crt);
2839 int  cl_page_cache_add  (const struct lu_env *env, struct cl_io *io,
2840                          struct cl_page *pg, enum cl_req_type crt);
2841 void cl_page_clip       (const struct lu_env *env, struct cl_page *pg,
2842                          int from, int to);
2843 int  cl_page_cancel     (const struct lu_env *env, struct cl_page *page);
2844 int  cl_page_flush      (const struct lu_env *env, struct cl_io *io,
2845                          struct cl_page *pg);
2846
2847 /** @} transfer */
2848
2849
2850 /**
2851  * \name helper routines
2852  * Functions to discard, delete and export a cl_page.
2853  */
2854 /** @{ */
2855 void    cl_page_discard      (const struct lu_env *env, struct cl_io *io,
2856                               struct cl_page *pg);
2857 void    cl_page_delete       (const struct lu_env *env, struct cl_page *pg);
2858 int     cl_page_unmap        (const struct lu_env *env, struct cl_io *io,
2859                               struct cl_page *pg);
2860 int     cl_page_is_vmlocked  (const struct lu_env *env,
2861                               const struct cl_page *pg);
2862 void    cl_page_export       (const struct lu_env *env,
2863                               struct cl_page *pg, int uptodate);
2864 int     cl_page_is_under_lock(const struct lu_env *env, struct cl_io *io,
2865                               struct cl_page *page);
2866 loff_t  cl_offset            (const struct cl_object *obj, pgoff_t idx);
2867 pgoff_t cl_index             (const struct cl_object *obj, loff_t offset);
2868 int     cl_page_size         (const struct cl_object *obj);
2869 int     cl_pages_prune       (const struct lu_env *env, struct cl_object *obj);
2870
2871 void cl_lock_print      (const struct lu_env *env, void *cookie,
2872                          lu_printer_t printer, const struct cl_lock *lock);
2873 void cl_lock_descr_print(const struct lu_env *env, void *cookie,
2874                          lu_printer_t printer,
2875                          const struct cl_lock_descr *descr);
2876 /* @} helper */
2877
2878 /** @} cl_page */
2879
2880 /** \defgroup cl_lock cl_lock
2881  * @{ */
2882
2883 struct cl_lock *cl_lock_hold(const struct lu_env *env, const struct cl_io *io,
2884                              const struct cl_lock_descr *need,
2885                              const char *scope, const void *source);
2886 struct cl_lock *cl_lock_peek(const struct lu_env *env, const struct cl_io *io,
2887                              const struct cl_lock_descr *need,
2888                              const char *scope, const void *source);
2889 struct cl_lock *cl_lock_request(const struct lu_env *env, struct cl_io *io,
2890                                 const struct cl_lock_descr *need,
2891                                 const char *scope, const void *source);
2892 struct cl_lock *cl_lock_at_pgoff(const struct lu_env *env,
2893                                  struct cl_object *obj, pgoff_t index,
2894                                  struct cl_lock *except, int pending,
2895                                  int canceld);
2896 static inline struct cl_lock *cl_lock_at_page(const struct lu_env *env,
2897                                               struct cl_object *obj,
2898                                               struct cl_page *page,
2899                                               struct cl_lock *except,
2900                                               int pending, int canceld)
2901 {
2902         LASSERT(cl_object_header(obj) == cl_object_header(page->cp_obj));
2903         return cl_lock_at_pgoff(env, obj, page->cp_index, except,
2904                                 pending, canceld);
2905 }
2906
2907 const struct cl_lock_slice *cl_lock_at(const struct cl_lock *lock,
2908                                        const struct lu_device_type *dtype);
2909
2910 void  cl_lock_get       (struct cl_lock *lock);
2911 void  cl_lock_get_trust (struct cl_lock *lock);
2912 void  cl_lock_put       (const struct lu_env *env, struct cl_lock *lock);
2913 void  cl_lock_hold_add  (const struct lu_env *env, struct cl_lock *lock,
2914                          const char *scope, const void *source);
2915 void cl_lock_hold_release(const struct lu_env *env, struct cl_lock *lock,
2916                           const char *scope, const void *source);
2917 void  cl_lock_unhold    (const struct lu_env *env, struct cl_lock *lock,
2918                          const char *scope, const void *source);
2919 void  cl_lock_release   (const struct lu_env *env, struct cl_lock *lock,
2920                          const char *scope, const void *source);
2921 void  cl_lock_user_add  (const struct lu_env *env, struct cl_lock *lock);
2922 void  cl_lock_user_del  (const struct lu_env *env, struct cl_lock *lock);
2923
2924 enum cl_lock_state cl_lock_intransit(const struct lu_env *env,
2925                                      struct cl_lock *lock);
2926 void cl_lock_extransit(const struct lu_env *env, struct cl_lock *lock,
2927                        enum cl_lock_state state);
2928 int cl_lock_is_intransit(struct cl_lock *lock);
2929
2930 int cl_lock_enqueue_wait(const struct lu_env *env, struct cl_lock *lock,
2931                          int keep_mutex);
2932
2933 /** \name statemachine statemachine
2934  * Interface to lock state machine consists of 3 parts:
2935  *
2936  *     - "try" functions that attempt to effect a state transition. If state
2937  *     transition is not possible right now (e.g., if it has to wait for some
2938  *     asynchronous event to occur), these functions return
2939  *     cl_lock_transition::CLO_WAIT.
2940  *
2941  *     - "non-try" functions that implement synchronous blocking interface on
2942  *     top of non-blocking "try" functions. These functions repeatedly call
2943  *     corresponding "try" versions, and if state transition is not possible
2944  *     immediately, wait for lock state change.
2945  *
2946  *     - methods from cl_lock_operations, called by "try" functions. Lock can
2947  *     be advanced to the target state only when all layers voted that they
2948  *     are ready for this transition. "Try" functions call methods under lock
2949  *     mutex. If a layer had to release a mutex, it re-acquires it and returns
2950  *     cl_lock_transition::CLO_REPEAT, causing "try" function to call all
2951  *     layers again.
2952  *
2953  * TRY              NON-TRY      METHOD                            FINAL STATE
2954  *
2955  * cl_enqueue_try() cl_enqueue() cl_lock_operations::clo_enqueue() CLS_ENQUEUED
2956  *
2957  * cl_wait_try()    cl_wait()    cl_lock_operations::clo_wait()    CLS_HELD
2958  *
2959  * cl_unuse_try()   cl_unuse()   cl_lock_operations::clo_unuse()   CLS_CACHED
2960  *
2961  * cl_use_try()     NONE         cl_lock_operations::clo_use()     CLS_HELD
2962  *
2963  * @{ */
2964
2965 int   cl_enqueue    (const struct lu_env *env, struct cl_lock *lock,
2966                      struct cl_io *io, __u32 flags);
2967 int   cl_wait       (const struct lu_env *env, struct cl_lock *lock);
2968 void  cl_unuse      (const struct lu_env *env, struct cl_lock *lock);
2969 int   cl_enqueue_try(const struct lu_env *env, struct cl_lock *lock,
2970                      struct cl_io *io, __u32 flags);
2971 int   cl_unuse_try  (const struct lu_env *env, struct cl_lock *lock);
2972 int   cl_wait_try   (const struct lu_env *env, struct cl_lock *lock);
2973 int   cl_use_try    (const struct lu_env *env, struct cl_lock *lock, int atomic);
2974
2975 /** @} statemachine */
2976
2977 void cl_lock_signal      (const struct lu_env *env, struct cl_lock *lock);
2978 int  cl_lock_state_wait  (const struct lu_env *env, struct cl_lock *lock);
2979 void cl_lock_state_set   (const struct lu_env *env, struct cl_lock *lock,
2980                           enum cl_lock_state state);
2981 int  cl_queue_match      (const cfs_list_t *queue,
2982                           const struct cl_lock_descr *need);
2983
2984 void cl_lock_mutex_get  (const struct lu_env *env, struct cl_lock *lock);
2985 int  cl_lock_mutex_try  (const struct lu_env *env, struct cl_lock *lock);
2986 void cl_lock_mutex_put  (const struct lu_env *env, struct cl_lock *lock);
2987 int  cl_lock_is_mutexed (struct cl_lock *lock);
2988 int  cl_lock_nr_mutexed (const struct lu_env *env);
2989 int  cl_lock_discard_pages(const struct lu_env *env, struct cl_lock *lock);
2990 int  cl_lock_ext_match  (const struct cl_lock_descr *has,
2991                          const struct cl_lock_descr *need);
2992 int  cl_lock_descr_match(const struct cl_lock_descr *has,
2993                          const struct cl_lock_descr *need);
2994 int  cl_lock_mode_match (enum cl_lock_mode has, enum cl_lock_mode need);
2995 int  cl_lock_modify     (const struct lu_env *env, struct cl_lock *lock,
2996                          const struct cl_lock_descr *desc);
2997
2998 void cl_lock_closure_init (const struct lu_env *env,
2999                            struct cl_lock_closure *closure,
3000                            struct cl_lock *origin, int wait);
3001 void cl_lock_closure_fini (struct cl_lock_closure *closure);
3002 int  cl_lock_closure_build(const struct lu_env *env, struct cl_lock *lock,
3003                            struct cl_lock_closure *closure);
3004 void cl_lock_disclosure   (const struct lu_env *env,
3005                            struct cl_lock_closure *closure);
3006 int  cl_lock_enclosure    (const struct lu_env *env, struct cl_lock *lock,
3007                            struct cl_lock_closure *closure);
3008
3009 void cl_lock_cancel(const struct lu_env *env, struct cl_lock *lock);
3010 void cl_lock_delete(const struct lu_env *env, struct cl_lock *lock);
3011 void cl_lock_error (const struct lu_env *env, struct cl_lock *lock, int error);
3012 void cl_locks_prune(const struct lu_env *env, struct cl_object *obj, int wait);
3013
3014 unsigned long cl_lock_weigh(const struct lu_env *env, struct cl_lock *lock);
3015
3016 /** @} cl_lock */
3017
3018 /** \defgroup cl_io cl_io
3019  * @{ */
3020
3021 int   cl_io_init         (const struct lu_env *env, struct cl_io *io,
3022                           enum cl_io_type iot, struct cl_object *obj);
3023 int   cl_io_sub_init     (const struct lu_env *env, struct cl_io *io,
3024                           enum cl_io_type iot, struct cl_object *obj);
3025 int   cl_io_rw_init      (const struct lu_env *env, struct cl_io *io,
3026                           enum cl_io_type iot, loff_t pos, size_t count);
3027 int   cl_io_loop         (const struct lu_env *env, struct cl_io *io);
3028
3029 void  cl_io_fini         (const struct lu_env *env, struct cl_io *io);
3030 int   cl_io_iter_init    (const struct lu_env *env, struct cl_io *io);
3031 void  cl_io_iter_fini    (const struct lu_env *env, struct cl_io *io);
3032 int   cl_io_lock         (const struct lu_env *env, struct cl_io *io);
3033 void  cl_io_unlock       (const struct lu_env *env, struct cl_io *io);
3034 int   cl_io_start        (const struct lu_env *env, struct cl_io *io);
3035 void  cl_io_end          (const struct lu_env *env, struct cl_io *io);
3036 int   cl_io_lock_add     (const struct lu_env *env, struct cl_io *io,
3037                           struct cl_io_lock_link *link);
3038 int   cl_io_lock_alloc_add(const struct lu_env *env, struct cl_io *io,
3039                            struct cl_lock_descr *descr);
3040 int   cl_io_read_page    (const struct lu_env *env, struct cl_io *io,
3041                           struct cl_page *page);
3042 int   cl_io_prepare_write(const struct lu_env *env, struct cl_io *io,
3043                           struct cl_page *page, unsigned from, unsigned to);
3044 int   cl_io_commit_write (const struct lu_env *env, struct cl_io *io,
3045                           struct cl_page *page, unsigned from, unsigned to);
3046 int   cl_io_submit_rw    (const struct lu_env *env, struct cl_io *io,
3047                           enum cl_req_type iot, struct cl_2queue *queue);
3048 int   cl_io_submit_sync  (const struct lu_env *env, struct cl_io *io,
3049                           enum cl_req_type iot, struct cl_2queue *queue,
3050                           long timeout);
3051 void  cl_io_rw_advance   (const struct lu_env *env, struct cl_io *io,
3052                           size_t nob);
3053 int   cl_io_cancel       (const struct lu_env *env, struct cl_io *io,
3054                           struct cl_page_list *queue);
3055 int   cl_io_is_going     (const struct lu_env *env);
3056
3057 /**
3058  * True, iff \a io is an O_APPEND write(2).
3059  */
3060 static inline int cl_io_is_append(const struct cl_io *io)
3061 {
3062         return io->ci_type == CIT_WRITE && io->u.ci_wr.wr_append;
3063 }
3064
3065 static inline int cl_io_is_sync_write(const struct cl_io *io)
3066 {
3067         return io->ci_type == CIT_WRITE && io->u.ci_wr.wr_sync;
3068 }
3069
3070 static inline int cl_io_is_mkwrite(const struct cl_io *io)
3071 {
3072         return io->ci_type == CIT_FAULT && io->u.ci_fault.ft_mkwrite;
3073 }
3074
3075 /**
3076  * True, iff \a io is a truncate(2).
3077  */
3078 static inline int cl_io_is_trunc(const struct cl_io *io)
3079 {
3080         return io->ci_type == CIT_SETATTR &&
3081                 (io->u.ci_setattr.sa_valid & ATTR_SIZE);
3082 }
3083
3084 struct cl_io *cl_io_top(struct cl_io *io);
3085
3086 void cl_io_print(const struct lu_env *env, void *cookie,
3087                  lu_printer_t printer, const struct cl_io *io);
3088
3089 #define CL_IO_SLICE_CLEAN(foo_io, base)                                 \
3090 do {                                                                    \
3091         typeof(foo_io) __foo_io = (foo_io);                             \
3092                                                                         \
3093         CLASSERT(offsetof(typeof(*__foo_io), base) == 0);               \
3094         memset(&__foo_io->base + 1, 0,                                  \
3095                (sizeof *__foo_io) - sizeof __foo_io->base);             \
3096 } while (0)
3097
3098 /** @} cl_io */
3099
3100 /** \defgroup cl_page_list cl_page_list
3101  * @{ */
3102
3103 /**
3104  * Last page in the page list.
3105  */
3106 static inline struct cl_page *cl_page_list_last(struct cl_page_list *plist)
3107 {
3108         LASSERT(plist->pl_nr > 0);
3109         return cfs_list_entry(plist->pl_pages.prev, struct cl_page, cp_batch);
3110 }
3111
3112 /**
3113  * Iterate over pages in a page list.
3114  */
3115 #define cl_page_list_for_each(page, list)                               \
3116         cfs_list_for_each_entry((page), &(list)->pl_pages, cp_batch)
3117
3118 /**
3119  * Iterate over pages in a page list, taking possible removals into account.
3120  */
3121 #define cl_page_list_for_each_safe(page, temp, list)                    \
3122         cfs_list_for_each_entry_safe((page), (temp), &(list)->pl_pages, cp_batch)
3123
3124 void cl_page_list_init   (struct cl_page_list *plist);
3125 void cl_page_list_add    (struct cl_page_list *plist, struct cl_page *page);
3126 void cl_page_list_move   (struct cl_page_list *dst, struct cl_page_list *src,
3127                           struct cl_page *page);
3128 void cl_page_list_splice (struct cl_page_list *list,
3129                           struct cl_page_list *head);
3130 void cl_page_list_del    (const struct lu_env *env,
3131                           struct cl_page_list *plist, struct cl_page *page);
3132 void cl_page_list_disown (const struct lu_env *env,
3133                           struct cl_io *io, struct cl_page_list *plist);
3134 int  cl_page_list_own    (const struct lu_env *env,
3135                           struct cl_io *io, struct cl_page_list *plist);
3136 void cl_page_list_assume (const struct lu_env *env,
3137                           struct cl_io *io, struct cl_page_list *plist);
3138 void cl_page_list_discard(const struct lu_env *env,
3139                           struct cl_io *io, struct cl_page_list *plist);
3140 int  cl_page_list_unmap  (const struct lu_env *env,
3141                           struct cl_io *io, struct cl_page_list *plist);
3142 void cl_page_list_fini   (const struct lu_env *env, struct cl_page_list *plist);
3143
3144 void cl_2queue_init     (struct cl_2queue *queue);
3145 void cl_2queue_add      (struct cl_2queue *queue, struct cl_page *page);
3146 void cl_2queue_disown   (const struct lu_env *env,
3147                          struct cl_io *io, struct cl_2queue *queue);
3148 void cl_2queue_assume   (const struct lu_env *env,
3149                          struct cl_io *io, struct cl_2queue *queue);
3150 void cl_2queue_discard  (const struct lu_env *env,
3151                          struct cl_io *io, struct cl_2queue *queue);
3152 void cl_2queue_fini     (const struct lu_env *env, struct cl_2queue *queue);
3153 void cl_2queue_init_page(struct cl_2queue *queue, struct cl_page *page);
3154
3155 /** @} cl_page_list */
3156
3157 /** \defgroup cl_req cl_req
3158  * @{ */
3159 struct cl_req *cl_req_alloc(const struct lu_env *env, struct cl_page *page,
3160                             enum cl_req_type crt, int nr_objects);
3161
3162 void cl_req_page_add  (const struct lu_env *env, struct cl_req *req,
3163                        struct cl_page *page);
3164 void cl_req_page_done (const struct lu_env *env, struct cl_page *page);
3165 int  cl_req_prep      (const struct lu_env *env, struct cl_req *req);
3166 void cl_req_attr_set  (const struct lu_env *env, struct cl_req *req,
3167                        struct cl_req_attr *attr, obd_valid flags);
3168 void cl_req_completion(const struct lu_env *env, struct cl_req *req, int ioret);
3169
3170 /** \defgroup cl_sync_io cl_sync_io
3171  * @{ */
3172
3173 /**
3174  * Anchor for synchronous transfer. This is allocated on a stack by thread
3175  * doing synchronous transfer, and a pointer to this structure is set up in
3176  * every page submitted for transfer. Transfer completion routine updates
3177  * anchor and wakes up waiting thread when transfer is complete.
3178  */
3179 struct cl_sync_io {
3180         /** number of pages yet to be transferred. */
3181         cfs_atomic_t          csi_sync_nr;
3182         /** completion to be signaled when transfer is complete. */
3183         cfs_waitq_t          csi_waitq;
3184         /** error code. */
3185         int                   csi_sync_rc;
3186 };
3187
3188 void cl_sync_io_init(struct cl_sync_io *anchor, int nrpages);
3189 int  cl_sync_io_wait(const struct lu_env *env, struct cl_io *io,
3190                      struct cl_page_list *queue, struct cl_sync_io *anchor,
3191                      long timeout);
3192 void cl_sync_io_note(struct cl_sync_io *anchor, int ioret);
3193
3194 /** @} cl_sync_io */
3195
3196 /** @} cl_req */
3197
3198 /** \defgroup cl_env cl_env
3199  *
3200  * lu_env handling for a client.
3201  *
3202  * lu_env is an environment within which lustre code executes. Its major part
3203  * is lu_context---a fast memory allocation mechanism that is used to conserve
3204  * precious kernel stack space. Originally lu_env was designed for a server,
3205  * where
3206  *
3207  *     - there is a (mostly) fixed number of threads, and
3208  *
3209  *     - call chains have no non-lustre portions inserted between lustre code.
3210  *
3211  * On a client both these assumtpion fails, because every user thread can
3212  * potentially execute lustre code as part of a system call, and lustre calls
3213  * into VFS or MM that call back into lustre.
3214  *
3215  * To deal with that, cl_env wrapper functions implement the following
3216  * optimizations:
3217  *
3218  *     - allocation and destruction of environment is amortized by caching no
3219  *     longer used environments instead of destroying them;
3220  *
3221  *     - there is a notion of "current" environment, attached to the kernel
3222  *     data structure representing current thread Top-level lustre code
3223  *     allocates an environment and makes it current, then calls into
3224  *     non-lustre code, that in turn calls lustre back. Low-level lustre
3225  *     code thus called can fetch environment created by the top-level code
3226  *     and reuse it, avoiding additional environment allocation.
3227  *       Right now, three interfaces can attach the cl_env to running thread:
3228  *       - cl_env_get
3229  *       - cl_env_implant
3230  *       - cl_env_reexit(cl_env_reenter had to be called priorly)
3231  *
3232  * \see lu_env, lu_context, lu_context_key
3233  * @{ */
3234
3235 struct cl_env_nest {
3236         int   cen_refcheck;
3237         void *cen_cookie;
3238 };
3239
3240 struct lu_env *cl_env_peek       (int *refcheck);
3241 struct lu_env *cl_env_get        (int *refcheck);
3242 struct lu_env *cl_env_alloc      (int *refcheck, __u32 tags);
3243 struct lu_env *cl_env_nested_get (struct cl_env_nest *nest);
3244 void           cl_env_put        (struct lu_env *env, int *refcheck);
3245 void           cl_env_nested_put (struct cl_env_nest *nest, struct lu_env *env);
3246 void          *cl_env_reenter    (void);
3247 void           cl_env_reexit     (void *cookie);
3248 void           cl_env_implant    (struct lu_env *env, int *refcheck);
3249 void           cl_env_unplant    (struct lu_env *env, int *refcheck);
3250 unsigned       cl_env_cache_purge(unsigned nr);
3251
3252 /** @} cl_env */
3253
3254 /*
3255  * Misc
3256  */
3257 void cl_attr2lvb(struct ost_lvb *lvb, const struct cl_attr *attr);
3258 void cl_lvb2attr(struct cl_attr *attr, const struct ost_lvb *lvb);
3259
3260 struct cl_device *cl_type_setup(const struct lu_env *env, struct lu_site *site,
3261                                 struct lu_device_type *ldt,
3262                                 struct lu_device *next);
3263 /** @} clio */
3264
3265 #endif /* _LINUX_CL_OBJECT_H */