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