Whamcloud - gitweb
LU-9771 clio: introduce CIT_GLIMPSE for glimpse
[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.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2016, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  */
32 #ifndef _LUSTRE_CL_OBJECT_H
33 #define _LUSTRE_CL_OBJECT_H
34
35 /** \defgroup clio clio
36  *
37  * Client objects implement io operations and cache pages.
38  *
39  * Examples: lov and osc are implementations of cl interface.
40  *
41  * Big Theory Statement.
42  *
43  * Layered objects.
44  *
45  * Client implementation is based on the following data-types:
46  *
47  *   - cl_object
48  *
49  *   - cl_page
50  *
51  *   - cl_lock     represents an extent lock on an object.
52  *
53  *   - cl_io       represents high-level i/o activity such as whole read/write
54  *                 system call, or write-out of pages from under the lock being
55  *                 canceled. cl_io has sub-ios that can be stopped and resumed
56  *                 independently, thus achieving high degree of transfer
57  *                 parallelism. Single cl_io can be advanced forward by
58  *                 the multiple threads (although in the most usual case of
59  *                 read/write system call it is associated with the single user
60  *                 thread, that issued the system call).
61  *
62  * Terminology
63  *
64  *     - to avoid confusion high-level I/O operation like read or write system
65  *     call is referred to as "an io", whereas low-level I/O operation, like
66  *     RPC, is referred to as "a transfer"
67  *
68  *     - "generic code" means generic (not file system specific) code in the
69  *     hosting environment. "cl-code" means code (mostly in cl_*.c files) that
70  *     is not layer specific.
71  *
72  * Locking.
73  *
74  *  - i_mutex
75  *      - PG_locked
76  *          - cl_object_header::coh_page_guard
77  *          - lu_site::ls_guard
78  *
79  * See the top comment in cl_object.c for the description of overall locking and
80  * reference-counting design.
81  *
82  * See comments below for the description of i/o, page, and dlm-locking
83  * design.
84  *
85  * @{
86  */
87
88 /*
89  * super-class definitions.
90  */
91 #include <libcfs/libcfs.h>
92 #include <libcfs/libcfs_ptask.h>
93 #include <lu_object.h>
94 #include <linux/atomic.h>
95 #include <linux/mutex.h>
96 #include <linux/radix-tree.h>
97 #include <linux/spinlock.h>
98 #include <linux/wait.h>
99 #include <lustre_dlm.h>
100
101 struct obd_info;
102 struct inode;
103
104 struct cl_device;
105
106 struct cl_object;
107
108 struct cl_page;
109 struct cl_page_slice;
110 struct cl_lock;
111 struct cl_lock_slice;
112
113 struct cl_lock_operations;
114 struct cl_page_operations;
115
116 struct cl_io;
117 struct cl_io_slice;
118
119 struct cl_req_attr;
120
121 extern struct cfs_ptask_engine *cl_io_engine;
122
123 /**
124  * Device in the client stack.
125  *
126  * \see vvp_device, lov_device, lovsub_device, osc_device
127  */
128 struct cl_device {
129         /** Super-class. */
130         struct lu_device                   cd_lu_dev;
131 };
132
133 /** \addtogroup cl_object cl_object
134  * @{ */
135 /**
136  * "Data attributes" of cl_object. Data attributes can be updated
137  * independently for a sub-object, and top-object's attributes are calculated
138  * from sub-objects' ones.
139  */
140 struct cl_attr {
141         /** Object size, in bytes */
142         loff_t cat_size;
143         /**
144          * Known minimal size, in bytes.
145          *
146          * This is only valid when at least one DLM lock is held.
147          */
148         loff_t cat_kms;
149         /** Modification time. Measured in seconds since epoch. */
150         time64_t cat_mtime;
151         /** Access time. Measured in seconds since epoch. */
152         time64_t cat_atime;
153         /** Change time. Measured in seconds since epoch. */
154         time64_t cat_ctime;
155         /**
156          * Blocks allocated to this cl_object on the server file system.
157          *
158          * \todo XXX An interface for block size is needed.
159          */
160         __u64  cat_blocks;
161         /**
162          * User identifier for quota purposes.
163          */
164         uid_t  cat_uid;
165         /**
166          * Group identifier for quota purposes.
167          */
168         gid_t  cat_gid;
169
170         /* nlink of the directory */
171         __u64  cat_nlink;
172
173         /* Project identifier for quota purpose. */
174         __u32  cat_projid;
175 };
176
177 /**
178  * Fields in cl_attr that are being set.
179  */
180 enum cl_attr_valid {
181         CAT_SIZE   = 1 << 0,
182         CAT_KMS    = 1 << 1,
183         CAT_MTIME  = 1 << 3,
184         CAT_ATIME  = 1 << 4,
185         CAT_CTIME  = 1 << 5,
186         CAT_BLOCKS = 1 << 6,
187         CAT_UID    = 1 << 7,
188         CAT_GID    = 1 << 8,
189         CAT_PROJID = 1 << 9
190 };
191
192 /**
193  * Sub-class of lu_object with methods common for objects on the client
194  * stacks.
195  *
196  * cl_object: represents a regular file system object, both a file and a
197  *    stripe. cl_object is based on lu_object: it is identified by a fid,
198  *    layered, cached, hashed, and lrued. Important distinction with the server
199  *    side, where md_object and dt_object are used, is that cl_object "fans out"
200  *    at the lov/sns level: depending on the file layout, single file is
201  *    represented as a set of "sub-objects" (stripes). At the implementation
202  *    level, struct lov_object contains an array of cl_objects. Each sub-object
203  *    is a full-fledged cl_object, having its fid, living in the lru and hash
204  *    table.
205  *
206  *    This leads to the next important difference with the server side: on the
207  *    client, it's quite usual to have objects with the different sequence of
208  *    layers. For example, typical top-object is composed of the following
209  *    layers:
210  *
211  *        - vvp
212  *        - lov
213  *
214  *    whereas its sub-objects are composed of
215  *
216  *        - lovsub
217  *        - osc
218  *
219  *    layers. Here "lovsub" is a mostly dummy layer, whose purpose is to keep
220  *    track of the object-subobject relationship.
221  *
222  *    Sub-objects are not cached independently: when top-object is about to
223  *    be discarded from the memory, all its sub-objects are torn-down and
224  *    destroyed too.
225  *
226  * \see vvp_object, lov_object, lovsub_object, osc_object
227  */
228 struct cl_object {
229         /** super class */
230         struct lu_object                   co_lu;
231         /** per-object-layer operations */
232         const struct cl_object_operations *co_ops;
233         /** offset of page slice in cl_page buffer */
234         int                                co_slice_off;
235 };
236
237 /**
238  * Description of the client object configuration. This is used for the
239  * creation of a new client object that is identified by a more state than
240  * fid.
241  */
242 struct cl_object_conf {
243         /** Super-class. */
244         struct lu_object_conf     coc_lu;
245         union {
246                 /**
247                  * Object layout. This is consumed by lov.
248                  */
249                 struct lu_buf    coc_layout;
250                 /**
251                  * Description of particular stripe location in the
252                  * cluster. This is consumed by osc.
253                  */
254                 struct lov_oinfo *coc_oinfo;
255         } u;
256         /**
257          * VFS inode. This is consumed by vvp.
258          */
259         struct inode             *coc_inode;
260         /**
261          * Layout lock handle.
262          */
263         struct ldlm_lock         *coc_lock;
264         /**
265          * Operation to handle layout, OBJECT_CONF_XYZ.
266          */
267         int                       coc_opc;
268 };
269
270 enum {
271         /** configure layout, set up a new stripe, must be called while
272          * holding layout lock. */
273         OBJECT_CONF_SET = 0,
274         /** invalidate the current stripe configuration due to losing
275          * layout lock. */
276         OBJECT_CONF_INVALIDATE = 1,
277         /** wait for old layout to go away so that new layout can be
278          * set up. */
279         OBJECT_CONF_WAIT = 2
280 };
281
282 enum {
283         CL_LAYOUT_GEN_NONE      = (u32)-2,      /* layout lock was cancelled */
284         CL_LAYOUT_GEN_EMPTY     = (u32)-1,      /* for empty layout */
285 };
286
287 struct cl_layout {
288         /** the buffer to return the layout in lov_mds_md format. */
289         struct lu_buf   cl_buf;
290         /** size of layout in lov_mds_md format. */
291         size_t          cl_size;
292         /** size of DoM component if exists or zero otherwise */
293         u64             cl_dom_comp_size;
294         /** Layout generation. */
295         u32             cl_layout_gen;
296         /** whether layout is a composite one */
297         bool            cl_is_composite;
298 };
299
300 /**
301  * Operations implemented for each cl object layer.
302  *
303  * \see vvp_ops, lov_ops, lovsub_ops, osc_ops
304  */
305 struct cl_object_operations {
306         /**
307          * Initialize page slice for this layer. Called top-to-bottom through
308          * every object layer when a new cl_page is instantiated. Layer
309          * keeping private per-page data, or requiring its own page operations
310          * vector should allocate these data here, and attach then to the page
311          * by calling cl_page_slice_add(). \a vmpage is locked (in the VM
312          * sense). Optional.
313          *
314          * \retval NULL success.
315          *
316          * \retval ERR_PTR(errno) failure code.
317          *
318          * \retval valid-pointer pointer to already existing referenced page
319          *         to be used instead of newly created.
320          */
321         int  (*coo_page_init)(const struct lu_env *env, struct cl_object *obj,
322                                 struct cl_page *page, pgoff_t index);
323         /**
324          * Initialize lock slice for this layer. Called top-to-bottom through
325          * every object layer when a new cl_lock is instantiated. Layer
326          * keeping private per-lock data, or requiring its own lock operations
327          * vector should allocate these data here, and attach then to the lock
328          * by calling cl_lock_slice_add(). Mandatory.
329          */
330         int  (*coo_lock_init)(const struct lu_env *env,
331                               struct cl_object *obj, struct cl_lock *lock,
332                               const struct cl_io *io);
333         /**
334          * Initialize io state for a given layer.
335          *
336          * called top-to-bottom once per io existence to initialize io
337          * state. If layer wants to keep some state for this type of io, it
338          * has to embed struct cl_io_slice in lu_env::le_ses, and register
339          * slice with cl_io_slice_add(). It is guaranteed that all threads
340          * participating in this io share the same session.
341          */
342         int  (*coo_io_init)(const struct lu_env *env,
343                             struct cl_object *obj, struct cl_io *io);
344         /**
345          * Fill portion of \a attr that this layer controls. This method is
346          * called top-to-bottom through all object layers.
347          *
348          * \pre cl_object_header::coh_attr_guard of the top-object is locked.
349          *
350          * \return   0: to continue
351          * \return +ve: to stop iterating through layers (but 0 is returned
352          *              from enclosing cl_object_attr_get())
353          * \return -ve: to signal error
354          */
355         int (*coo_attr_get)(const struct lu_env *env, struct cl_object *obj,
356                             struct cl_attr *attr);
357         /**
358          * Update attributes.
359          *
360          * \a valid is a bitmask composed from enum #cl_attr_valid, and
361          * indicating what attributes are to be set.
362          *
363          * \pre cl_object_header::coh_attr_guard of the top-object is locked.
364          *
365          * \return the same convention as for
366          * cl_object_operations::coo_attr_get() is used.
367          */
368         int (*coo_attr_update)(const struct lu_env *env, struct cl_object *obj,
369                                const struct cl_attr *attr, unsigned valid);
370         /**
371          * Update object configuration. Called top-to-bottom to modify object
372          * configuration.
373          *
374          * XXX error conditions and handling.
375          */
376         int (*coo_conf_set)(const struct lu_env *env, struct cl_object *obj,
377                             const struct cl_object_conf *conf);
378         /**
379          * Glimpse ast. Executed when glimpse ast arrives for a lock on this
380          * object. Layers are supposed to fill parts of \a lvb that will be
381          * shipped to the glimpse originator as a glimpse result.
382          *
383          * \see vvp_object_glimpse(), lovsub_object_glimpse(),
384          * \see osc_object_glimpse()
385          */
386         int (*coo_glimpse)(const struct lu_env *env,
387                            const struct cl_object *obj, struct ost_lvb *lvb);
388         /**
389          * Object prune method. Called when the layout is going to change on
390          * this object, therefore each layer has to clean up their cache,
391          * mainly pages and locks.
392          */
393         int (*coo_prune)(const struct lu_env *env, struct cl_object *obj);
394         /**
395          * Object getstripe method.
396          */
397         int (*coo_getstripe)(const struct lu_env *env, struct cl_object *obj,
398                              struct lov_user_md __user *lum, size_t size);
399         /**
400          * Get FIEMAP mapping from the object.
401          */
402         int (*coo_fiemap)(const struct lu_env *env, struct cl_object *obj,
403                           struct ll_fiemap_info_key *fmkey,
404                           struct fiemap *fiemap, size_t *buflen);
405         /**
406          * Get layout and generation of the object.
407          */
408         int (*coo_layout_get)(const struct lu_env *env, struct cl_object *obj,
409                               struct cl_layout *layout);
410         /**
411          * Get maximum size of the object.
412          */
413         loff_t (*coo_maxbytes)(struct cl_object *obj);
414         /**
415          * Set request attributes.
416          */
417         void (*coo_req_attr_set)(const struct lu_env *env,
418                                  struct cl_object *obj,
419                                  struct cl_req_attr *attr);
420 };
421
422 /**
423  * Extended header for client object.
424  */
425 struct cl_object_header {
426         /** Standard lu_object_header. cl_object::co_lu::lo_header points
427          * here. */
428         struct lu_object_header coh_lu;
429
430         /**
431          * Parent object. It is assumed that an object has a well-defined
432          * parent, but not a well-defined child (there may be multiple
433          * sub-objects, for the same top-object). cl_object_header::coh_parent
434          * field allows certain code to be written generically, without
435          * limiting possible cl_object layouts unduly.
436          */
437         struct cl_object_header *coh_parent;
438         /**
439          * Protects consistency between cl_attr of parent object and
440          * attributes of sub-objects, that the former is calculated ("merged")
441          * from.
442          *
443          * \todo XXX this can be read/write lock if needed.
444          */
445         spinlock_t               coh_attr_guard;
446         /**
447          * Size of cl_page + page slices
448          */
449         unsigned short           coh_page_bufsize;
450         /**
451          * Number of objects above this one: 0 for a top-object, 1 for its
452          * sub-object, etc.
453          */
454         unsigned char            coh_nesting;
455 };
456
457 /**
458  * Helper macro: iterate over all layers of the object \a obj, assigning every
459  * layer top-to-bottom to \a slice.
460  */
461 #define cl_object_for_each(slice, obj)                          \
462         list_for_each_entry((slice),                            \
463                             &(obj)->co_lu.lo_header->loh_layers,\
464                             co_lu.lo_linkage)
465
466 /**
467  * Helper macro: iterate over all layers of the object \a obj, assigning every
468  * layer bottom-to-top to \a slice.
469  */
470 #define cl_object_for_each_reverse(slice, obj)                          \
471         list_for_each_entry_reverse((slice),                            \
472                                     &(obj)->co_lu.lo_header->loh_layers,\
473                                     co_lu.lo_linkage)
474
475 /** @} cl_object */
476
477 #define CL_PAGE_EOF ((pgoff_t)~0ull)
478
479 /** \addtogroup cl_page cl_page
480  * @{ */
481
482 /** \struct cl_page
483  * Layered client page.
484  *
485  * cl_page: represents a portion of a file, cached in the memory. All pages
486  *    of the given file are of the same size, and are kept in the radix tree
487  *    hanging off the cl_object. cl_page doesn't fan out, but as sub-objects
488  *    of the top-level file object are first class cl_objects, they have their
489  *    own radix trees of pages and hence page is implemented as a sequence of
490  *    struct cl_pages's, linked into double-linked list through
491  *    cl_page::cp_parent and cl_page::cp_child pointers, each residing in the
492  *    corresponding radix tree at the corresponding logical offset.
493  *
494  * cl_page is associated with VM page of the hosting environment (struct
495  *    page in Linux kernel, for example), struct page. It is assumed, that this
496  *    association is implemented by one of cl_page layers (top layer in the
497  *    current design) that
498  *
499  *        - intercepts per-VM-page call-backs made by the environment (e.g.,
500  *          memory pressure),
501  *
502  *        - translates state (page flag bits) and locking between lustre and
503  *          environment.
504  *
505  *    The association between cl_page and struct page is immutable and
506  *    established when cl_page is created.
507  *
508  * cl_page can be "owned" by a particular cl_io (see below), guaranteeing
509  *    this io an exclusive access to this page w.r.t. other io attempts and
510  *    various events changing page state (such as transfer completion, or
511  *    eviction of the page from the memory). Note, that in general cl_io
512  *    cannot be identified with a particular thread, and page ownership is not
513  *    exactly equal to the current thread holding a lock on the page. Layer
514  *    implementing association between cl_page and struct page has to implement
515  *    ownership on top of available synchronization mechanisms.
516  *
517  *    While lustre client maintains the notion of an page ownership by io,
518  *    hosting MM/VM usually has its own page concurrency control
519  *    mechanisms. For example, in Linux, page access is synchronized by the
520  *    per-page PG_locked bit-lock, and generic kernel code (generic_file_*())
521  *    takes care to acquire and release such locks as necessary around the
522  *    calls to the file system methods (->readpage(), ->prepare_write(),
523  *    ->commit_write(), etc.). This leads to the situation when there are two
524  *    different ways to own a page in the client:
525  *
526  *        - client code explicitly and voluntary owns the page (cl_page_own());
527  *
528  *        - VM locks a page and then calls the client, that has "to assume"
529  *          the ownership from the VM (cl_page_assume()).
530  *
531  *    Dual methods to release ownership are cl_page_disown() and
532  *    cl_page_unassume().
533  *
534  * cl_page is reference counted (cl_page::cp_ref). When reference counter
535  *    drops to 0, the page is returned to the cache, unless it is in
536  *    cl_page_state::CPS_FREEING state, in which case it is immediately
537  *    destroyed.
538  *
539  *    The general logic guaranteeing the absence of "existential races" for
540  *    pages is the following:
541  *
542  *        - there are fixed known ways for a thread to obtain a new reference
543  *          to a page:
544  *
545  *            - by doing a lookup in the cl_object radix tree, protected by the
546  *              spin-lock;
547  *
548  *            - by starting from VM-locked struct page and following some
549  *              hosting environment method (e.g., following ->private pointer in
550  *              the case of Linux kernel), see cl_vmpage_page();
551  *
552  *        - when the page enters cl_page_state::CPS_FREEING state, all these
553  *          ways are severed with the proper synchronization
554  *          (cl_page_delete());
555  *
556  *        - entry into cl_page_state::CPS_FREEING is serialized by the VM page
557  *          lock;
558  *
559  *        - no new references to the page in cl_page_state::CPS_FREEING state
560  *          are allowed (checked in cl_page_get()).
561  *
562  *    Together this guarantees that when last reference to a
563  *    cl_page_state::CPS_FREEING page is released, it is safe to destroy the
564  *    page, as neither references to it can be acquired at that point, nor
565  *    ones exist.
566  *
567  * cl_page is a state machine. States are enumerated in enum
568  *    cl_page_state. Possible state transitions are enumerated in
569  *    cl_page_state_set(). State transition process (i.e., actual changing of
570  *    cl_page::cp_state field) is protected by the lock on the underlying VM
571  *    page.
572  *
573  * Linux Kernel implementation.
574  *
575  *    Binding between cl_page and struct page (which is a typedef for
576  *    struct page) is implemented in the vvp layer. cl_page is attached to the
577  *    ->private pointer of the struct page, together with the setting of
578  *    PG_private bit in page->flags, and acquiring additional reference on the
579  *    struct page (much like struct buffer_head, or any similar file system
580  *    private data structures).
581  *
582  *    PG_locked lock is used to implement both ownership and transfer
583  *    synchronization, that is, page is VM-locked in CPS_{OWNED,PAGE{IN,OUT}}
584  *    states. No additional references are acquired for the duration of the
585  *    transfer.
586  *
587  * \warning *THIS IS NOT* the behavior expected by the Linux kernel, where
588  *          write-out is "protected" by the special PG_writeback bit.
589  */
590
591 /**
592  * States of cl_page. cl_page.c assumes particular order here.
593  *
594  * The page state machine is rather crude, as it doesn't recognize finer page
595  * states like "dirty" or "up to date". This is because such states are not
596  * always well defined for the whole stack (see, for example, the
597  * implementation of the read-ahead, that hides page up-to-dateness to track
598  * cache hits accurately). Such sub-states are maintained by the layers that
599  * are interested in them.
600  */
601 enum cl_page_state {
602         /**
603          * Page is in the cache, un-owned. Page leaves cached state in the
604          * following cases:
605          *
606          *     - [cl_page_state::CPS_OWNED] io comes across the page and
607          *     owns it;
608          *
609          *     - [cl_page_state::CPS_PAGEOUT] page is dirty, the
610          *     req-formation engine decides that it wants to include this page
611          *     into an RPC being constructed, and yanks it from the cache;
612          *
613          *     - [cl_page_state::CPS_FREEING] VM callback is executed to
614          *     evict the page form the memory;
615          *
616          * \invariant cl_page::cp_owner == NULL && cl_page::cp_req == NULL
617          */
618         CPS_CACHED,
619         /**
620          * Page is exclusively owned by some cl_io. Page may end up in this
621          * state as a result of
622          *
623          *     - io creating new page and immediately owning it;
624          *
625          *     - [cl_page_state::CPS_CACHED] io finding existing cached page
626          *     and owning it;
627          *
628          *     - [cl_page_state::CPS_OWNED] io finding existing owned page
629          *     and waiting for owner to release the page;
630          *
631          * Page leaves owned state in the following cases:
632          *
633          *     - [cl_page_state::CPS_CACHED] io decides to leave the page in
634          *     the cache, doing nothing;
635          *
636          *     - [cl_page_state::CPS_PAGEIN] io starts read transfer for
637          *     this page;
638          *
639          *     - [cl_page_state::CPS_PAGEOUT] io starts immediate write
640          *     transfer for this page;
641          *
642          *     - [cl_page_state::CPS_FREEING] io decides to destroy this
643          *     page (e.g., as part of truncate or extent lock cancellation).
644          *
645          * \invariant cl_page::cp_owner != NULL && cl_page::cp_req == NULL
646          */
647         CPS_OWNED,
648         /**
649          * Page is being written out, as a part of a transfer. This state is
650          * entered when req-formation logic decided that it wants this page to
651          * be sent through the wire _now_. Specifically, it means that once
652          * this state is achieved, transfer completion handler (with either
653          * success or failure indication) is guaranteed to be executed against
654          * this page independently of any locks and any scheduling decisions
655          * made by the hosting environment (that effectively means that the
656          * page is never put into cl_page_state::CPS_PAGEOUT state "in
657          * advance". This property is mentioned, because it is important when
658          * reasoning about possible dead-locks in the system). The page can
659          * enter this state as a result of
660          *
661          *     - [cl_page_state::CPS_OWNED] an io requesting an immediate
662          *     write-out of this page, or
663          *
664          *     - [cl_page_state::CPS_CACHED] req-forming engine deciding
665          *     that it has enough dirty pages cached to issue a "good"
666          *     transfer.
667          *
668          * The page leaves cl_page_state::CPS_PAGEOUT state when the transfer
669          * is completed---it is moved into cl_page_state::CPS_CACHED state.
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_PAGEOUT,
676         /**
677          * Page is being read in, as a part of a transfer. This is quite
678          * similar to the cl_page_state::CPS_PAGEOUT state, except that
679          * read-in is always "immediate"---there is no such thing a sudden
680          * construction of read request from cached, presumably not up to date,
681          * pages.
682          *
683          * Underlying VM page is locked for the duration of transfer.
684          *
685          * \invariant: cl_page::cp_owner == NULL && cl_page::cp_req != NULL
686          */
687         CPS_PAGEIN,
688         /**
689          * Page is being destroyed. This state is entered when client decides
690          * that page has to be deleted from its host object, as, e.g., a part
691          * of truncate.
692          *
693          * Once this state is reached, there is no way to escape it.
694          *
695          * \invariant: cl_page::cp_owner == NULL && cl_page::cp_req == NULL
696          */
697         CPS_FREEING,
698         CPS_NR
699 };
700
701 enum cl_page_type {
702         /** Host page, the page is from the host inode which the cl_page
703          * belongs to. */
704         CPT_CACHEABLE = 1,
705
706         /** Transient page, the transient cl_page is used to bind a cl_page
707          *  to vmpage which is not belonging to the same object of cl_page.
708          *  it is used in DirectIO and lockless IO. */
709         CPT_TRANSIENT,
710 };
711
712 /**
713  * Fields are protected by the lock on struct page, except for atomics and
714  * immutables.
715  *
716  * \invariant Data type invariants are in cl_page_invariant(). Basically:
717  * cl_page::cp_parent and cl_page::cp_child are a well-formed double-linked
718  * list, consistent with the parent/child pointers in the cl_page::cp_obj and
719  * cl_page::cp_owner (when set).
720  */
721 struct cl_page {
722         /** Reference counter. */
723         atomic_t                 cp_ref;
724         /** An object this page is a part of. Immutable after creation. */
725         struct cl_object        *cp_obj;
726         /** vmpage */
727         struct page             *cp_vmpage;
728         /** Linkage of pages within group. Pages must be owned */
729         struct list_head         cp_batch;
730         /** List of slices. Immutable after creation. */
731         struct list_head         cp_layers;
732         /**
733          * Page state. This field is const to avoid accidental update, it is
734          * modified only internally within cl_page.c. Protected by a VM lock.
735          */
736         const enum cl_page_state cp_state;
737         /**
738          * Page type. Only CPT_TRANSIENT is used so far. Immutable after
739          * creation.
740          */
741         enum cl_page_type        cp_type;
742
743         /**
744          * Owning IO in cl_page_state::CPS_OWNED state. Sub-page can be owned
745          * by sub-io. Protected by a VM lock.
746          */
747         struct cl_io            *cp_owner;
748         /** List of references to this page, for debugging. */
749         struct lu_ref            cp_reference;
750         /** Link to an object, for debugging. */
751         struct lu_ref_link       cp_obj_ref;
752         /** Link to a queue, for debugging. */
753         struct lu_ref_link       cp_queue_ref;
754         /** Assigned if doing a sync_io */
755         struct cl_sync_io       *cp_sync_io;
756 };
757
758 /**
759  * Per-layer part of cl_page.
760  *
761  * \see vvp_page, lov_page, osc_page
762  */
763 struct cl_page_slice {
764         struct cl_page                  *cpl_page;
765         pgoff_t                          cpl_index;
766         /**
767          * Object slice corresponding to this page slice. Immutable after
768          * creation.
769          */
770         struct cl_object                *cpl_obj;
771         const struct cl_page_operations *cpl_ops;
772         /** Linkage into cl_page::cp_layers. Immutable after creation. */
773         struct list_head                 cpl_linkage;
774 };
775
776 /**
777  * Lock mode. For the client extent locks.
778  *
779  * \ingroup cl_lock
780  */
781 enum cl_lock_mode {
782         CLM_READ,
783         CLM_WRITE,
784         CLM_GROUP,
785         CLM_MAX,
786 };
787
788 /**
789  * Requested transfer type.
790  */
791 enum cl_req_type {
792         CRT_READ,
793         CRT_WRITE,
794         CRT_NR
795 };
796
797 /**
798  * Per-layer page operations.
799  *
800  * Methods taking an \a io argument are for the activity happening in the
801  * context of given \a io. Page is assumed to be owned by that io, except for
802  * the obvious cases (like cl_page_operations::cpo_own()).
803  *
804  * \see vvp_page_ops, lov_page_ops, osc_page_ops
805  */
806 struct cl_page_operations {
807         /**
808          * cl_page<->struct page methods. Only one layer in the stack has to
809          * implement these. Current code assumes that this functionality is
810          * provided by the topmost layer, see cl_page_disown0() as an example.
811          */
812
813         /**
814          * Called when \a io acquires this page into the exclusive
815          * ownership. When this method returns, it is guaranteed that the is
816          * not owned by other io, and no transfer is going on against
817          * it. Optional.
818          *
819          * \see cl_page_own()
820          * \see vvp_page_own(), lov_page_own()
821          */
822         int  (*cpo_own)(const struct lu_env *env,
823                         const struct cl_page_slice *slice,
824                         struct cl_io *io, int nonblock);
825         /** Called when ownership it yielded. Optional.
826          *
827          * \see cl_page_disown()
828          * \see vvp_page_disown()
829          */
830         void (*cpo_disown)(const struct lu_env *env,
831                            const struct cl_page_slice *slice, struct cl_io *io);
832         /**
833          * Called for a page that is already "owned" by \a io from VM point of
834          * view. Optional.
835          *
836          * \see cl_page_assume()
837          * \see vvp_page_assume(), lov_page_assume()
838          */
839         void (*cpo_assume)(const struct lu_env *env,
840                            const struct cl_page_slice *slice, struct cl_io *io);
841         /** Dual to cl_page_operations::cpo_assume(). Optional. Called
842          * bottom-to-top when IO releases a page without actually unlocking
843          * it.
844          *
845          * \see cl_page_unassume()
846          * \see vvp_page_unassume()
847          */
848         void (*cpo_unassume)(const struct lu_env *env,
849                              const struct cl_page_slice *slice,
850                              struct cl_io *io);
851         /**
852          * Announces whether the page contains valid data or not by \a uptodate.
853          *
854          * \see cl_page_export()
855          * \see vvp_page_export()
856          */
857         void  (*cpo_export)(const struct lu_env *env,
858                             const struct cl_page_slice *slice, int uptodate);
859         /**
860          * Checks whether underlying VM page is locked (in the suitable
861          * sense). Used for assertions.
862          *
863          * \retval    -EBUSY: page is protected by a lock of a given mode;
864          * \retval  -ENODATA: page is not protected by a lock;
865          * \retval         0: this layer cannot decide. (Should never happen.)
866          */
867         int (*cpo_is_vmlocked)(const struct lu_env *env,
868                                const struct cl_page_slice *slice);
869         /**
870          * Page destruction.
871          */
872
873         /**
874          * Called when page is truncated from the object. Optional.
875          *
876          * \see cl_page_discard()
877          * \see vvp_page_discard(), osc_page_discard()
878          */
879         void (*cpo_discard)(const struct lu_env *env,
880                             const struct cl_page_slice *slice,
881                             struct cl_io *io);
882         /**
883          * Called when page is removed from the cache, and is about to being
884          * destroyed. Optional.
885          *
886          * \see cl_page_delete()
887          * \see vvp_page_delete(), osc_page_delete()
888          */
889         void (*cpo_delete)(const struct lu_env *env,
890                            const struct cl_page_slice *slice);
891         /** Destructor. Frees resources and slice itself. */
892         void (*cpo_fini)(const struct lu_env *env,
893                          struct cl_page_slice *slice);
894         /**
895          * Optional debugging helper. Prints given page slice.
896          *
897          * \see cl_page_print()
898          */
899         int (*cpo_print)(const struct lu_env *env,
900                          const struct cl_page_slice *slice,
901                          void *cookie, lu_printer_t p);
902         /**
903          * \name transfer
904          *
905          * Transfer methods.
906          *
907          * @{
908          */
909         /**
910          * Request type dependent vector of operations.
911          *
912          * Transfer operations depend on transfer mode (cl_req_type). To avoid
913          * passing transfer mode to each and every of these methods, and to
914          * avoid branching on request type inside of the methods, separate
915          * methods for cl_req_type:CRT_READ and cl_req_type:CRT_WRITE are
916          * provided. That is, method invocation usually looks like
917          *
918          *         slice->cp_ops.io[req->crq_type].cpo_method(env, slice, ...);
919          */
920         struct {
921                 /**
922                  * Called when a page is submitted for a transfer as a part of
923                  * cl_page_list.
924                  *
925                  * \return    0         : page is eligible for submission;
926                  * \return    -EALREADY : skip this page;
927                  * \return    -ve       : error.
928                  *
929                  * \see cl_page_prep()
930                  */
931                 int  (*cpo_prep)(const struct lu_env *env,
932                                  const struct cl_page_slice *slice,
933                                  struct cl_io *io);
934                 /**
935                  * Completion handler. This is guaranteed to be eventually
936                  * fired after cl_page_operations::cpo_prep() or
937                  * cl_page_operations::cpo_make_ready() call.
938                  *
939                  * This method can be called in a non-blocking context. It is
940                  * guaranteed however, that the page involved and its object
941                  * are pinned in memory (and, hence, calling cl_page_put() is
942                  * safe).
943                  *
944                  * \see cl_page_completion()
945                  */
946                 void (*cpo_completion)(const struct lu_env *env,
947                                        const struct cl_page_slice *slice,
948                                        int ioret);
949                 /**
950                  * Called when cached page is about to be added to the
951                  * ptlrpc request as a part of req formation.
952                  *
953                  * \return    0       : proceed with this page;
954                  * \return    -EAGAIN : skip this page;
955                  * \return    -ve     : error.
956                  *
957                  * \see cl_page_make_ready()
958                  */
959                 int  (*cpo_make_ready)(const struct lu_env *env,
960                                        const struct cl_page_slice *slice);
961         } io[CRT_NR];
962         /**
963          * Tell transfer engine that only [to, from] part of a page should be
964          * transmitted.
965          *
966          * This is used for immediate transfers.
967          *
968          * \todo XXX this is not very good interface. It would be much better
969          * if all transfer parameters were supplied as arguments to
970          * cl_io_operations::cio_submit() call, but it is not clear how to do
971          * this for page queues.
972          *
973          * \see cl_page_clip()
974          */
975         void (*cpo_clip)(const struct lu_env *env,
976                          const struct cl_page_slice *slice,
977                          int from, int to);
978         /**
979          * \pre  the page was queued for transferring.
980          * \post page is removed from client's pending list, or -EBUSY
981          *       is returned if it has already been in transferring.
982          *
983          * This is one of seldom page operation which is:
984          * 0. called from top level;
985          * 1. don't have vmpage locked;
986          * 2. every layer should synchronize execution of its ->cpo_cancel()
987          *    with completion handlers. Osc uses client obd lock for this
988          *    purpose. Based on there is no vvp_page_cancel and
989          *    lov_page_cancel(), cpo_cancel is defacto protected by client lock.
990          *
991          * \see osc_page_cancel().
992          */
993         int (*cpo_cancel)(const struct lu_env *env,
994                           const struct cl_page_slice *slice);
995         /**
996          * Write out a page by kernel. This is only called by ll_writepage
997          * right now.
998          *
999          * \see cl_page_flush()
1000          */
1001         int (*cpo_flush)(const struct lu_env *env,
1002                          const struct cl_page_slice *slice,
1003                          struct cl_io *io);
1004         /** @} transfer */
1005 };
1006
1007 /**
1008  * Helper macro, dumping detailed information about \a page into a log.
1009  */
1010 #define CL_PAGE_DEBUG(mask, env, page, format, ...)                     \
1011 do {                                                                    \
1012         if (cfs_cdebug_show(mask, DEBUG_SUBSYSTEM)) {                   \
1013                 LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, mask, NULL);        \
1014                 cl_page_print(env, &msgdata, lu_cdebug_printer, page);  \
1015                 CDEBUG(mask, format , ## __VA_ARGS__);                  \
1016         }                                                               \
1017 } while (0)
1018
1019 /**
1020  * Helper macro, dumping shorter information about \a page into a log.
1021  */
1022 #define CL_PAGE_HEADER(mask, env, page, format, ...)                          \
1023 do {                                                                          \
1024         if (cfs_cdebug_show(mask, DEBUG_SUBSYSTEM)) {                         \
1025                 LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, mask, NULL);              \
1026                 cl_page_header_print(env, &msgdata, lu_cdebug_printer, page); \
1027                 CDEBUG(mask, format , ## __VA_ARGS__);                        \
1028         }                                                                     \
1029 } while (0)
1030
1031 static inline struct page *cl_page_vmpage(const struct cl_page *page)
1032 {
1033         LASSERT(page->cp_vmpage != NULL);
1034         return page->cp_vmpage;
1035 }
1036
1037 /**
1038  * Check if a cl_page is in use.
1039  *
1040  * Client cache holds a refcount, this refcount will be dropped when
1041  * the page is taken out of cache, see vvp_page_delete().
1042  */
1043 static inline bool __page_in_use(const struct cl_page *page, int refc)
1044 {
1045         return (atomic_read(&page->cp_ref) > refc + 1);
1046 }
1047
1048 /**
1049  * Caller itself holds a refcount of cl_page.
1050  */
1051 #define cl_page_in_use(pg)       __page_in_use(pg, 1)
1052 /**
1053  * Caller doesn't hold a refcount.
1054  */
1055 #define cl_page_in_use_noref(pg) __page_in_use(pg, 0)
1056
1057 /** @} cl_page */
1058
1059 /** \addtogroup cl_lock cl_lock
1060  * @{ */
1061 /** \struct cl_lock
1062  *
1063  * Extent locking on the client.
1064  *
1065  * LAYERING
1066  *
1067  * The locking model of the new client code is built around
1068  *
1069  *        struct cl_lock
1070  *
1071  * data-type representing an extent lock on a regular file. cl_lock is a
1072  * layered object (much like cl_object and cl_page), it consists of a header
1073  * (struct cl_lock) and a list of layers (struct cl_lock_slice), linked to
1074  * cl_lock::cll_layers list through cl_lock_slice::cls_linkage.
1075  *
1076  * Typical cl_lock consists of the two layers:
1077  *
1078  *     - vvp_lock (vvp specific data), and
1079  *     - lov_lock (lov specific data).
1080  *
1081  * lov_lock contains an array of sub-locks. Each of these sub-locks is a
1082  * normal cl_lock: it has a header (struct cl_lock) and a list of layers:
1083  *
1084  *     - lovsub_lock, and
1085  *     - osc_lock
1086  *
1087  * Each sub-lock is associated with a cl_object (representing stripe
1088  * sub-object or the file to which top-level cl_lock is associated to), and is
1089  * linked into that cl_object::coh_locks. In this respect cl_lock is similar to
1090  * cl_object (that at lov layer also fans out into multiple sub-objects), and
1091  * is different from cl_page, that doesn't fan out (there is usually exactly
1092  * one osc_page for every vvp_page). We shall call vvp-lov portion of the lock
1093  * a "top-lock" and its lovsub-osc portion a "sub-lock".
1094  *
1095  * LIFE CYCLE
1096  *
1097  * cl_lock is a cacheless data container for the requirements of locks to
1098  * complete the IO. cl_lock is created before I/O starts and destroyed when the
1099  * I/O is complete.
1100  *
1101  * cl_lock depends on LDLM lock to fulfill lock semantics. LDLM lock is attached
1102  * to cl_lock at OSC layer. LDLM lock is still cacheable.
1103  *
1104  * INTERFACE AND USAGE
1105  *
1106  * Two major methods are supported for cl_lock: clo_enqueue and clo_cancel.  A
1107  * cl_lock is enqueued by cl_lock_request(), which will call clo_enqueue()
1108  * methods for each layer to enqueue the lock. At the LOV layer, if a cl_lock
1109  * consists of multiple sub cl_locks, each sub locks will be enqueued
1110  * correspondingly. At OSC layer, the lock enqueue request will tend to reuse
1111  * cached LDLM lock; otherwise a new LDLM lock will have to be requested from
1112  * OST side.
1113  *
1114  * cl_lock_cancel() must be called to release a cl_lock after use. clo_cancel()
1115  * method will be called for each layer to release the resource held by this
1116  * lock. At OSC layer, the reference count of LDLM lock, which is held at
1117  * clo_enqueue time, is released.
1118  *
1119  * LDLM lock can only be canceled if there is no cl_lock using it.
1120  *
1121  * Overall process of the locking during IO operation is as following:
1122  *
1123  *     - once parameters for IO are setup in cl_io, cl_io_operations::cio_lock()
1124  *       is called on each layer. Responsibility of this method is to add locks,
1125  *       needed by a given layer into cl_io.ci_lockset.
1126  *
1127  *     - once locks for all layers were collected, they are sorted to avoid
1128  *       dead-locks (cl_io_locks_sort()), and enqueued.
1129  *
1130  *     - when all locks are acquired, IO is performed;
1131  *
1132  *     - locks are released after IO is complete.
1133  *
1134  * Striping introduces major additional complexity into locking. The
1135  * fundamental problem is that it is generally unsafe to actively use (hold)
1136  * two locks on the different OST servers at the same time, as this introduces
1137  * inter-server dependency and can lead to cascading evictions.
1138  *
1139  * Basic solution is to sub-divide large read/write IOs into smaller pieces so
1140  * that no multi-stripe locks are taken (note that this design abandons POSIX
1141  * read/write semantics). Such pieces ideally can be executed concurrently. At
1142  * the same time, certain types of IO cannot be sub-divived, without
1143  * sacrificing correctness. This includes:
1144  *
1145  *  - O_APPEND write, where [0, EOF] lock has to be taken, to guarantee
1146  *  atomicity;
1147  *
1148  *  - ftruncate(fd, offset), where [offset, EOF] lock has to be taken.
1149  *
1150  * Also, in the case of read(fd, buf, count) or write(fd, buf, count), where
1151  * buf is a part of memory mapped Lustre file, a lock or locks protecting buf
1152  * has to be held together with the usual lock on [offset, offset + count].
1153  *
1154  * Interaction with DLM
1155  *
1156  * In the expected setup, cl_lock is ultimately backed up by a collection of
1157  * DLM locks (struct ldlm_lock). Association between cl_lock and DLM lock is
1158  * implemented in osc layer, that also matches DLM events (ASTs, cancellation,
1159  * etc.) into cl_lock_operation calls. See struct osc_lock for a more detailed
1160  * description of interaction with DLM.
1161  */
1162
1163 /**
1164  * Lock description.
1165  */
1166 struct cl_lock_descr {
1167         /** Object this lock is granted for. */
1168         struct cl_object *cld_obj;
1169         /** Index of the first page protected by this lock. */
1170         pgoff_t           cld_start;
1171         /** Index of the last page (inclusive) protected by this lock. */
1172         pgoff_t           cld_end;
1173         /** Group ID, for group lock */
1174         __u64             cld_gid;
1175         /** Lock mode. */
1176         enum cl_lock_mode cld_mode;
1177         /**
1178          * flags to enqueue lock. A combination of bit-flags from
1179          * enum cl_enq_flags.
1180          */
1181         __u32             cld_enq_flags;
1182 };
1183
1184 #define DDESCR "%s(%d):[%lu, %lu]:%x"
1185 #define PDESCR(descr)                                                   \
1186         cl_lock_mode_name((descr)->cld_mode), (descr)->cld_mode,        \
1187         (descr)->cld_start, (descr)->cld_end, (descr)->cld_enq_flags
1188
1189 const char *cl_lock_mode_name(const enum cl_lock_mode mode);
1190
1191 /**
1192  * Layered client lock.
1193  */
1194 struct cl_lock {
1195         /** List of slices. Immutable after creation. */
1196         struct list_head      cll_layers;
1197         /** lock attribute, extent, cl_object, etc. */
1198         struct cl_lock_descr  cll_descr;
1199 };
1200
1201 /**
1202  * Per-layer part of cl_lock
1203  *
1204  * \see vvp_lock, lov_lock, lovsub_lock, osc_lock
1205  */
1206 struct cl_lock_slice {
1207         struct cl_lock                  *cls_lock;
1208         /** Object slice corresponding to this lock slice. Immutable after
1209          * creation. */
1210         struct cl_object                *cls_obj;
1211         const struct cl_lock_operations *cls_ops;
1212         /** Linkage into cl_lock::cll_layers. Immutable after creation. */
1213         struct list_head                 cls_linkage;
1214 };
1215
1216 /**
1217  *
1218  * \see vvp_lock_ops, lov_lock_ops, lovsub_lock_ops, osc_lock_ops
1219  */
1220 struct cl_lock_operations {
1221         /** @{ */
1222         /**
1223          * Attempts to enqueue the lock. Called top-to-bottom.
1224          *
1225          * \retval 0    this layer has enqueued the lock successfully
1226          * \retval >0   this layer has enqueued the lock, but need to wait on
1227          *              @anchor for resources
1228          * \retval -ve  failure
1229          *
1230          * \see vvp_lock_enqueue(), lov_lock_enqueue(), lovsub_lock_enqueue(),
1231          * \see osc_lock_enqueue()
1232          */
1233         int  (*clo_enqueue)(const struct lu_env *env,
1234                             const struct cl_lock_slice *slice,
1235                             struct cl_io *io, struct cl_sync_io *anchor);
1236         /**
1237          * Cancel a lock, release its DLM lock ref, while does not cancel the
1238          * DLM lock
1239          */
1240         void (*clo_cancel)(const struct lu_env *env,
1241                            const struct cl_lock_slice *slice);
1242         /** @} */
1243         /**
1244          * Destructor. Frees resources and the slice.
1245          *
1246          * \see vvp_lock_fini(), lov_lock_fini(), lovsub_lock_fini(),
1247          * \see osc_lock_fini()
1248          */
1249         void (*clo_fini)(const struct lu_env *env, struct cl_lock_slice *slice);
1250         /**
1251          * Optional debugging helper. Prints given lock slice.
1252          */
1253         int (*clo_print)(const struct lu_env *env,
1254                          void *cookie, lu_printer_t p,
1255                          const struct cl_lock_slice *slice);
1256 };
1257
1258 #define CL_LOCK_DEBUG(mask, env, lock, format, ...)                     \
1259 do {                                                                    \
1260         if (cfs_cdebug_show(mask, DEBUG_SUBSYSTEM)) {                   \
1261                 LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, mask, NULL);        \
1262                 cl_lock_print(env, &msgdata, lu_cdebug_printer, lock);  \
1263                 CDEBUG(mask, format , ## __VA_ARGS__);                  \
1264         }                                                               \
1265 } while (0)
1266
1267 #define CL_LOCK_ASSERT(expr, env, lock) do {                            \
1268         if (likely(expr))                                               \
1269                 break;                                                  \
1270                                                                         \
1271         CL_LOCK_DEBUG(D_ERROR, env, lock, "failed at %s.\n", #expr);    \
1272         LBUG();                                                         \
1273 } while (0)
1274
1275 /** @} cl_lock */
1276
1277 /** \addtogroup cl_page_list cl_page_list
1278  * Page list used to perform collective operations on a group of pages.
1279  *
1280  * Pages are added to the list one by one. cl_page_list acquires a reference
1281  * for every page in it. Page list is used to perform collective operations on
1282  * pages:
1283  *
1284  *     - submit pages for an immediate transfer,
1285  *
1286  *     - own pages on behalf of certain io (waiting for each page in turn),
1287  *
1288  *     - discard pages.
1289  *
1290  * When list is finalized, it releases references on all pages it still has.
1291  *
1292  * \todo XXX concurrency control.
1293  *
1294  * @{
1295  */
1296 struct cl_page_list {
1297         unsigned                 pl_nr;
1298         struct list_head         pl_pages;
1299         struct task_struct      *pl_owner;
1300 };
1301
1302 /** 
1303  * A 2-queue of pages. A convenience data-type for common use case, 2-queue
1304  * contains an incoming page list and an outgoing page list.
1305  */
1306 struct cl_2queue {
1307         struct cl_page_list c2_qin;
1308         struct cl_page_list c2_qout;
1309 };
1310
1311 /** @} cl_page_list */
1312
1313 /** \addtogroup cl_io cl_io
1314  * @{ */
1315 /** \struct cl_io
1316  * I/O
1317  *
1318  * cl_io represents a high level I/O activity like
1319  * read(2)/write(2)/truncate(2) system call, or cancellation of an extent
1320  * lock.
1321  *
1322  * cl_io is a layered object, much like cl_{object,page,lock} but with one
1323  * important distinction. We want to minimize number of calls to the allocator
1324  * in the fast path, e.g., in the case of read(2) when everything is cached:
1325  * client already owns the lock over region being read, and data are cached
1326  * due to read-ahead. To avoid allocation of cl_io layers in such situations,
1327  * per-layer io state is stored in the session, associated with the io, see
1328  * struct {vvp,lov,osc}_io for example. Sessions allocation is amortized
1329  * by using free-lists, see cl_env_get().
1330  *
1331  * There is a small predefined number of possible io types, enumerated in enum
1332  * cl_io_type.
1333  *
1334  * cl_io is a state machine, that can be advanced concurrently by the multiple
1335  * threads. It is up to these threads to control the concurrency and,
1336  * specifically, to detect when io is done, and its state can be safely
1337  * released.
1338  *
1339  * For read/write io overall execution plan is as following:
1340  *
1341  *     (0) initialize io state through all layers;
1342  *
1343  *     (1) loop: prepare chunk of work to do
1344  *
1345  *     (2) call all layers to collect locks they need to process current chunk
1346  *
1347  *     (3) sort all locks to avoid dead-locks, and acquire them
1348  *
1349  *     (4) process the chunk: call per-page methods
1350  *         cl_io_operations::cio_prepare_write(),
1351  *         cl_io_operations::cio_commit_write() for write)
1352  *
1353  *     (5) release locks
1354  *
1355  *     (6) repeat loop.
1356  *
1357  * To implement the "parallel IO mode", lov layer creates sub-io's (lazily to
1358  * address allocation efficiency issues mentioned above), and returns with the
1359  * special error condition from per-page method when current sub-io has to
1360  * block. This causes io loop to be repeated, and lov switches to the next
1361  * sub-io in its cl_io_operations::cio_iter_init() implementation.
1362  */
1363
1364 /** IO types */
1365 enum cl_io_type {
1366         /** read system call */
1367         CIT_READ = 1,
1368         /** write system call */
1369         CIT_WRITE,
1370         /** truncate, utime system calls */
1371         CIT_SETATTR,
1372         /** get data version */
1373         CIT_DATA_VERSION,
1374         /**
1375          * page fault handling
1376          */
1377         CIT_FAULT,
1378         /**
1379          * fsync system call handling
1380          * To write out a range of file
1381          */
1382         CIT_FSYNC,
1383         /**
1384          * glimpse. An io context to acquire glimpse lock.
1385          */
1386         CIT_GLIMPSE,
1387         /**
1388          * Miscellaneous io. This is used for occasional io activity that
1389          * doesn't fit into other types. Currently this is used for:
1390          *
1391          *     - cancellation of an extent lock. This io exists as a context
1392          *     to write dirty pages from under the lock being canceled back
1393          *     to the server;
1394          *
1395          *     - VM induced page write-out. An io context for writing page out
1396          *     for memory cleansing;
1397          *
1398          *     - grouplock. An io context to acquire group lock.
1399          *
1400          * CIT_MISC io is used simply as a context in which locks and pages
1401          * are manipulated. Such io has no internal "process", that is,
1402          * cl_io_loop() is never called for it.
1403          */
1404         CIT_MISC,
1405         /**
1406          * ladvise handling
1407          * To give advice about access of a file
1408          */
1409         CIT_LADVISE,
1410         CIT_OP_NR
1411 };
1412
1413 /**
1414  * States of cl_io state machine
1415  */
1416 enum cl_io_state {
1417         /** Not initialized. */
1418         CIS_ZERO,
1419         /** Initialized. */
1420         CIS_INIT,
1421         /** IO iteration started. */
1422         CIS_IT_STARTED,
1423         /** Locks taken. */
1424         CIS_LOCKED,
1425         /** Actual IO is in progress. */
1426         CIS_IO_GOING,
1427         /** IO for the current iteration finished. */
1428         CIS_IO_FINISHED,
1429         /** Locks released. */
1430         CIS_UNLOCKED,
1431         /** Iteration completed. */
1432         CIS_IT_ENDED,
1433         /** cl_io finalized. */
1434         CIS_FINI
1435 };
1436
1437 /**
1438  * IO state private for a layer.
1439  *
1440  * This is usually embedded into layer session data, rather than allocated
1441  * dynamically.
1442  *
1443  * \see vvp_io, lov_io, osc_io
1444  */
1445 struct cl_io_slice {
1446         struct cl_io                    *cis_io;
1447         /** corresponding object slice. Immutable after creation. */
1448         struct cl_object                *cis_obj;
1449         /** io operations. Immutable after creation. */
1450         const struct cl_io_operations   *cis_iop;
1451         /**
1452          * linkage into a list of all slices for a given cl_io, hanging off
1453          * cl_io::ci_layers. Immutable after creation.
1454          */
1455         struct list_head                cis_linkage;
1456 };
1457
1458 typedef void (*cl_commit_cbt)(const struct lu_env *, struct cl_io *,
1459                               struct cl_page *);
1460
1461 struct cl_read_ahead {
1462         /* Maximum page index the readahead window will end.
1463          * This is determined DLM lock coverage, RPC and stripe boundary.
1464          * cra_end is included. */
1465         pgoff_t cra_end;
1466         /* optimal RPC size for this read, by pages */
1467         unsigned long cra_rpc_size;
1468         /* Release callback. If readahead holds resources underneath, this
1469          * function should be called to release it. */
1470         void    (*cra_release)(const struct lu_env *env, void *cbdata);
1471         /* Callback data for cra_release routine */
1472         void    *cra_cbdata;
1473 };
1474
1475 static inline void cl_read_ahead_release(const struct lu_env *env,
1476                                          struct cl_read_ahead *ra)
1477 {
1478         if (ra->cra_release != NULL)
1479                 ra->cra_release(env, ra->cra_cbdata);
1480         memset(ra, 0, sizeof(*ra));
1481 }
1482
1483
1484 /**
1485  * Per-layer io operations.
1486  * \see vvp_io_ops, lov_io_ops, lovsub_io_ops, osc_io_ops
1487  */
1488 struct cl_io_operations {
1489         /**
1490          * Vector of io state transition methods for every io type.
1491          *
1492          * \see cl_page_operations::io
1493          */
1494         struct {
1495                 /**
1496                  * Prepare io iteration at a given layer.
1497                  *
1498                  * Called top-to-bottom at the beginning of each iteration of
1499                  * "io loop" (if it makes sense for this type of io). Here
1500                  * layer selects what work it will do during this iteration.
1501                  *
1502                  * \see cl_io_operations::cio_iter_fini()
1503                  */
1504                 int (*cio_iter_init) (const struct lu_env *env,
1505                                       const struct cl_io_slice *slice);
1506                 /**
1507                  * Finalize io iteration.
1508                  *
1509                  * Called bottom-to-top at the end of each iteration of "io
1510                  * loop". Here layers can decide whether IO has to be
1511                  * continued.
1512                  *
1513                  * \see cl_io_operations::cio_iter_init()
1514                  */
1515                 void (*cio_iter_fini) (const struct lu_env *env,
1516                                        const struct cl_io_slice *slice);
1517                 /**
1518                  * Collect locks for the current iteration of io.
1519                  *
1520                  * Called top-to-bottom to collect all locks necessary for
1521                  * this iteration. This methods shouldn't actually enqueue
1522                  * anything, instead it should post a lock through
1523                  * cl_io_lock_add(). Once all locks are collected, they are
1524                  * sorted and enqueued in the proper order.
1525                  */
1526                 int  (*cio_lock) (const struct lu_env *env,
1527                                   const struct cl_io_slice *slice);
1528                 /**
1529                  * Finalize unlocking.
1530                  *
1531                  * Called bottom-to-top to finish layer specific unlocking
1532                  * functionality, after generic code released all locks
1533                  * acquired by cl_io_operations::cio_lock().
1534                  */
1535                 void  (*cio_unlock)(const struct lu_env *env,
1536                                     const struct cl_io_slice *slice);
1537                 /**
1538                  * Start io iteration.
1539                  *
1540                  * Once all locks are acquired, called top-to-bottom to
1541                  * commence actual IO. In the current implementation,
1542                  * top-level vvp_io_{read,write}_start() does all the work
1543                  * synchronously by calling generic_file_*(), so other layers
1544                  * are called when everything is done.
1545                  */
1546                 int  (*cio_start)(const struct lu_env *env,
1547                                   const struct cl_io_slice *slice);
1548                 /**
1549                  * Called top-to-bottom at the end of io loop. Here layer
1550                  * might wait for an unfinished asynchronous io.
1551                  */
1552                 void (*cio_end)  (const struct lu_env *env,
1553                                   const struct cl_io_slice *slice);
1554                 /**
1555                  * Called bottom-to-top to notify layers that read/write IO
1556                  * iteration finished, with \a nob bytes transferred.
1557                  */
1558                 void (*cio_advance)(const struct lu_env *env,
1559                                     const struct cl_io_slice *slice,
1560                                     size_t nob);
1561                 /**
1562                  * Called once per io, bottom-to-top to release io resources.
1563                  */
1564                 void (*cio_fini) (const struct lu_env *env,
1565                                   const struct cl_io_slice *slice);
1566         } op[CIT_OP_NR];
1567
1568         /**
1569          * Submit pages from \a queue->c2_qin for IO, and move
1570          * successfully submitted pages into \a queue->c2_qout. Return
1571          * non-zero if failed to submit even the single page. If
1572          * submission failed after some pages were moved into \a
1573          * queue->c2_qout, completion callback with non-zero ioret is
1574          * executed on them.
1575          */
1576         int  (*cio_submit)(const struct lu_env *env,
1577                         const struct cl_io_slice *slice,
1578                         enum cl_req_type crt,
1579                         struct cl_2queue *queue);
1580         /**
1581          * Queue async page for write.
1582          * The difference between cio_submit and cio_queue is that
1583          * cio_submit is for urgent request.
1584          */
1585         int  (*cio_commit_async)(const struct lu_env *env,
1586                         const struct cl_io_slice *slice,
1587                         struct cl_page_list *queue, int from, int to,
1588                         cl_commit_cbt cb);
1589         /**
1590          * Decide maximum read ahead extent
1591          *
1592          * \pre io->ci_type == CIT_READ
1593          */
1594         int (*cio_read_ahead)(const struct lu_env *env,
1595                               const struct cl_io_slice *slice,
1596                               pgoff_t start, struct cl_read_ahead *ra);
1597         /**
1598          * Optional debugging helper. Print given io slice.
1599          */
1600         int (*cio_print)(const struct lu_env *env, void *cookie,
1601                          lu_printer_t p, const struct cl_io_slice *slice);
1602 };
1603
1604 /**
1605  * Flags to lock enqueue procedure.
1606  * \ingroup cl_lock
1607  */
1608 enum cl_enq_flags {
1609         /**
1610          * instruct server to not block, if conflicting lock is found. Instead
1611          * -EWOULDBLOCK is returned immediately.
1612          */
1613         CEF_NONBLOCK     = 0x00000001,
1614         /**
1615          * Tell lower layers this is a glimpse request, translated to
1616          * LDLM_FL_HAS_INTENT at LDLM layer.
1617          *
1618          * Also, because glimpse locks never block other locks, we count this
1619          * as automatically compatible with other osc locks.
1620          * (see osc_lock_compatible)
1621          */
1622         CEF_GLIMPSE        = 0x00000002,
1623         /**
1624          * tell the server to instruct (though a flag in the blocking ast) an
1625          * owner of the conflicting lock, that it can drop dirty pages
1626          * protected by this lock, without sending them to the server.
1627          */
1628         CEF_DISCARD_DATA = 0x00000004,
1629         /**
1630          * tell the sub layers that it must be a `real' lock. This is used for
1631          * mmapped-buffer locks, glimpse locks, manually requested locks
1632          * (LU_LADVISE_LOCKAHEAD) that must never be converted into lockless
1633          * mode.
1634          *
1635          * \see vvp_mmap_locks(), cl_glimpse_lock, cl_request_lock().
1636          */
1637         CEF_MUST         = 0x00000008,
1638         /**
1639          * tell the sub layers that never request a `real' lock. This flag is
1640          * not used currently.
1641          *
1642          * cl_io::ci_lockreq and CEF_{MUST,NEVER} flags specify lockless
1643          * conversion policy: ci_lockreq describes generic information of lock
1644          * requirement for this IO, especially for locks which belong to the
1645          * object doing IO; however, lock itself may have precise requirements
1646          * that are described by the enqueue flags.
1647          */
1648         CEF_NEVER        = 0x00000010,
1649         /**
1650          * tell the dlm layer this is a speculative lock request
1651          * speculative lock requests are locks which are not requested as part
1652          * of an I/O operation.  Instead, they are requested because we expect
1653          * to use them in the future.  They are requested asynchronously at the
1654          * ptlrpc layer.
1655          *
1656          * Currently used for asynchronous glimpse locks and manually requested
1657          * locks (LU_LADVISE_LOCKAHEAD).
1658          */
1659         CEF_SPECULATIVE          = 0x00000020,
1660         /**
1661          * enqueue a lock to test DLM lock existence.
1662          */
1663         CEF_PEEK        = 0x00000040,
1664         /**
1665          * Lock match only. Used by group lock in I/O as group lock
1666          * is known to exist.
1667          */
1668         CEF_LOCK_MATCH  = 0x00000080,
1669         /**
1670          * tell the DLM layer to lock only the requested range
1671          */
1672         CEF_LOCK_NO_EXPAND    = 0x00000100,
1673         /**
1674          * mask of enq_flags.
1675          */
1676         CEF_MASK         = 0x000001ff,
1677 };
1678
1679 /**
1680  * Link between lock and io. Intermediate structure is needed, because the
1681  * same lock can be part of multiple io's simultaneously.
1682  */
1683 struct cl_io_lock_link {
1684         /** linkage into one of cl_lockset lists. */
1685         struct list_head        cill_linkage;
1686         struct cl_lock          cill_lock;
1687         /** optional destructor */
1688         void                    (*cill_fini)(const struct lu_env *env,
1689                                              struct cl_io_lock_link *link);
1690 };
1691 #define cill_descr      cill_lock.cll_descr
1692
1693 /**
1694  * Lock-set represents a collection of locks, that io needs at a
1695  * time. Generally speaking, client tries to avoid holding multiple locks when
1696  * possible, because
1697  *
1698  *      - holding extent locks over multiple ost's introduces the danger of
1699  *        "cascading timeouts";
1700  *
1701  *      - holding multiple locks over the same ost is still dead-lock prone,
1702  *        see comment in osc_lock_enqueue(),
1703  *
1704  * but there are certain situations where this is unavoidable:
1705  *
1706  *      - O_APPEND writes have to take [0, EOF] lock for correctness;
1707  *
1708  *      - truncate has to take [new-size, EOF] lock for correctness;
1709  *
1710  *      - SNS has to take locks across full stripe for correctness;
1711  *
1712  *      - in the case when user level buffer, supplied to {read,write}(file0),
1713  *        is a part of a memory mapped lustre file, client has to take a dlm
1714  *        locks on file0, and all files that back up the buffer (or a part of
1715  *        the buffer, that is being processed in the current chunk, in any
1716  *        case, there are situations where at least 2 locks are necessary).
1717  *
1718  * In such cases we at least try to take locks in the same consistent
1719  * order. To this end, all locks are first collected, then sorted, and then
1720  * enqueued.
1721  */
1722 struct cl_lockset {
1723         /** locks to be acquired. */
1724         struct list_head  cls_todo;
1725         /** locks acquired. */
1726         struct list_head  cls_done;
1727 };
1728
1729 /**
1730  * Lock requirements(demand) for IO. It should be cl_io_lock_req,
1731  * but 'req' is always to be thought as 'request' :-)
1732  */
1733 enum cl_io_lock_dmd {
1734         /** Always lock data (e.g., O_APPEND). */
1735         CILR_MANDATORY = 0,
1736         /** Layers are free to decide between local and global locking. */
1737         CILR_MAYBE,
1738         /** Never lock: there is no cache (e.g., liblustre). */
1739         CILR_NEVER
1740 };
1741
1742 enum cl_fsync_mode {
1743         /** start writeback, do not wait for them to finish */
1744         CL_FSYNC_NONE  = 0,
1745         /** start writeback and wait for them to finish */
1746         CL_FSYNC_LOCAL = 1,
1747         /** discard all of dirty pages in a specific file range */
1748         CL_FSYNC_DISCARD = 2,
1749         /** start writeback and make sure they have reached storage before
1750          * return. OST_SYNC RPC must be issued and finished */
1751         CL_FSYNC_ALL   = 3
1752 };
1753
1754 struct cl_io_range {
1755         loff_t cir_pos;
1756         size_t cir_count;
1757 };
1758
1759 struct cl_io_pt {
1760         struct cl_io_pt         *cip_next;
1761         struct cfs_ptask         cip_task;
1762         struct kiocb             cip_iocb;
1763         struct iov_iter          cip_iter;
1764         struct file             *cip_file;
1765         enum cl_io_type          cip_iot;
1766         loff_t                   cip_pos;
1767         size_t                   cip_count;
1768         ssize_t                  cip_result;
1769 };
1770
1771 /**
1772  * State for io.
1773  *
1774  * cl_io is shared by all threads participating in this IO (in current
1775  * implementation only one thread advances IO, but parallel IO design and
1776  * concurrent copy_*_user() require multiple threads acting on the same IO. It
1777  * is up to these threads to serialize their activities, including updates to
1778  * mutable cl_io fields.
1779  */
1780 struct cl_io {
1781         /** type of this IO. Immutable after creation. */
1782         enum cl_io_type                ci_type;
1783         /** current state of cl_io state machine. */
1784         enum cl_io_state               ci_state;
1785         /** main object this io is against. Immutable after creation. */
1786         struct cl_object              *ci_obj;
1787         /**
1788          * Upper layer io, of which this io is a part of. Immutable after
1789          * creation.
1790          */
1791         struct cl_io                  *ci_parent;
1792         /** List of slices. Immutable after creation. */
1793         struct list_head                ci_layers;
1794         /** list of locks (to be) acquired by this io. */
1795         struct cl_lockset              ci_lockset;
1796         /** lock requirements, this is just a help info for sublayers. */
1797         enum cl_io_lock_dmd            ci_lockreq;
1798         union {
1799                 struct cl_rw_io {
1800                         struct iov_iter          rw_iter;
1801                         struct kiocb             rw_iocb;
1802                         struct cl_io_range       rw_range;
1803                         struct file             *rw_file;
1804                         unsigned int             rw_nonblock:1,
1805                                                  rw_append:1,
1806                                                  rw_sync:1;
1807                         int (*rw_ptask)(struct cfs_ptask *ptask);
1808                 } ci_rw;
1809                 struct cl_setattr_io {
1810                         struct ost_lvb           sa_attr;
1811                         unsigned int             sa_attr_flags;
1812                         unsigned int             sa_valid;
1813                         int                      sa_stripe_index;
1814                         struct ost_layout        sa_layout;
1815                         const struct lu_fid     *sa_parent_fid;
1816                 } ci_setattr;
1817                 struct cl_data_version_io {
1818                         u64 dv_data_version;
1819                         int dv_flags;
1820                 } ci_data_version;
1821                 struct cl_fault_io {
1822                         /** page index within file. */
1823                         pgoff_t         ft_index;
1824                         /** bytes valid byte on a faulted page. */
1825                         size_t          ft_nob;
1826                         /** writable page? for nopage() only */
1827                         int             ft_writable;
1828                         /** page of an executable? */
1829                         int             ft_executable;
1830                         /** page_mkwrite() */
1831                         int             ft_mkwrite;
1832                         /** resulting page */
1833                         struct cl_page *ft_page;
1834                 } ci_fault;
1835                 struct cl_fsync_io {
1836                         loff_t             fi_start;
1837                         loff_t             fi_end;
1838                         /** file system level fid */
1839                         struct lu_fid     *fi_fid;
1840                         enum cl_fsync_mode fi_mode;
1841                         /* how many pages were written/discarded */
1842                         unsigned int       fi_nr_written;
1843                 } ci_fsync;
1844                 struct cl_ladvise_io {
1845                         __u64                    li_start;
1846                         __u64                    li_end;
1847                         /** file system level fid */
1848                         struct lu_fid           *li_fid;
1849                         enum lu_ladvise_type     li_advice;
1850                         __u64                    li_flags;
1851                 } ci_ladvise;
1852         } u;
1853         struct cl_2queue     ci_queue;
1854         size_t               ci_nob;
1855         int                  ci_result;
1856         unsigned int         ci_continue:1,
1857         /**
1858          * This io has held grouplock, to inform sublayers that
1859          * don't do lockless i/o.
1860          */
1861                              ci_no_srvlock:1,
1862         /**
1863          * The whole IO need to be restarted because layout has been changed
1864          */
1865                              ci_need_restart:1,
1866         /**
1867          * to not refresh layout - the IO issuer knows that the layout won't
1868          * change(page operations, layout change causes all page to be
1869          * discarded), or it doesn't matter if it changes(sync).
1870          */
1871                              ci_ignore_layout:1,
1872         /**
1873          * Need MDS intervention to complete a write. This usually means the
1874          * corresponding component is not initialized for the writing extent.
1875          */
1876                              ci_need_write_intent:1,
1877         /**
1878          * Check if layout changed after the IO finishes. Mainly for HSM
1879          * requirement. If IO occurs to openning files, it doesn't need to
1880          * verify layout because HSM won't release openning files.
1881          * Right now, only two opertaions need to verify layout: glimpse
1882          * and setattr.
1883          */
1884                              ci_verify_layout:1,
1885         /**
1886          * file is released, restore has to to be triggered by vvp layer
1887          */
1888                              ci_restore_needed:1,
1889         /**
1890          * O_NOATIME
1891          */
1892                              ci_noatime:1,
1893         /** Set to 1 if parallel execution is allowed for current I/O? */
1894                              ci_pio:1,
1895         /* Tell sublayers not to expand LDLM locks requested for this IO */
1896                              ci_lock_no_expand:1;
1897         /**
1898          * Number of pages owned by this IO. For invariant checking.
1899          */
1900         unsigned             ci_owned_nr;
1901 };
1902
1903 /** @} cl_io */
1904
1905 /**
1906  * Per-transfer attributes.
1907  */
1908 struct cl_req_attr {
1909         enum cl_req_type cra_type;
1910         u64              cra_flags;
1911         struct cl_page  *cra_page;
1912         /** Generic attributes for the server consumption. */
1913         struct obdo     *cra_oa;
1914         /** Jobid */
1915         char             cra_jobid[LUSTRE_JOBID_SIZE];
1916 };
1917
1918 enum cache_stats_item {
1919         /** how many cache lookups were performed */
1920         CS_lookup = 0,
1921         /** how many times cache lookup resulted in a hit */
1922         CS_hit,
1923         /** how many entities are in the cache right now */
1924         CS_total,
1925         /** how many entities in the cache are actively used (and cannot be
1926          * evicted) right now */
1927         CS_busy,
1928         /** how many entities were created at all */
1929         CS_create,
1930         CS_NR
1931 };
1932
1933 #define CS_NAMES { "lookup", "hit", "total", "busy", "create" }
1934
1935 /**
1936  * Stats for a generic cache (similar to inode, lu_object, etc. caches).
1937  */
1938 struct cache_stats {
1939         const char      *cs_name;
1940         atomic_t        cs_stats[CS_NR];
1941 };
1942
1943 /** These are not exported so far */
1944 void cache_stats_init (struct cache_stats *cs, const char *name);
1945
1946 /**
1947  * Client-side site. This represents particular client stack. "Global"
1948  * variables should (directly or indirectly) be added here to allow multiple
1949  * clients to co-exist in the single address space.
1950  */
1951 struct cl_site {
1952         struct lu_site          cs_lu;
1953         /**
1954          * Statistical counters. Atomics do not scale, something better like
1955          * per-cpu counters is needed.
1956          *
1957          * These are exported as /proc/fs/lustre/llite/.../site
1958          *
1959          * When interpreting keep in mind that both sub-locks (and sub-pages)
1960          * and top-locks (and top-pages) are accounted here.
1961          */
1962         struct cache_stats      cs_pages;
1963         atomic_t                cs_pages_state[CPS_NR];
1964 };
1965
1966 int  cl_site_init(struct cl_site *s, struct cl_device *top);
1967 void cl_site_fini(struct cl_site *s);
1968 void cl_stack_fini(const struct lu_env *env, struct cl_device *cl);
1969
1970 /**
1971  * Output client site statistical counters into a buffer. Suitable for
1972  * ll_rd_*()-style functions.
1973  */
1974 int cl_site_stats_print(const struct cl_site *site, struct seq_file *m);
1975
1976 /**
1977  * \name helpers
1978  *
1979  * Type conversion and accessory functions.
1980  */
1981 /** @{ */
1982
1983 static inline struct cl_site *lu2cl_site(const struct lu_site *site)
1984 {
1985         return container_of(site, struct cl_site, cs_lu);
1986 }
1987
1988 static inline struct cl_device *lu2cl_dev(const struct lu_device *d)
1989 {
1990         LASSERT(d == NULL || IS_ERR(d) || lu_device_is_cl(d));
1991         return container_of0(d, struct cl_device, cd_lu_dev);
1992 }
1993
1994 static inline struct lu_device *cl2lu_dev(struct cl_device *d)
1995 {
1996         return &d->cd_lu_dev;
1997 }
1998
1999 static inline struct cl_object *lu2cl(const struct lu_object *o)
2000 {
2001         LASSERT(o == NULL || IS_ERR(o) || lu_device_is_cl(o->lo_dev));
2002         return container_of0(o, struct cl_object, co_lu);
2003 }
2004
2005 static inline const struct cl_object_conf *
2006 lu2cl_conf(const struct lu_object_conf *conf)
2007 {
2008         return container_of0(conf, struct cl_object_conf, coc_lu);
2009 }
2010
2011 static inline struct cl_object *cl_object_next(const struct cl_object *obj)
2012 {
2013         return obj ? lu2cl(lu_object_next(&obj->co_lu)) : NULL;
2014 }
2015
2016 static inline struct cl_object_header *luh2coh(const struct lu_object_header *h)
2017 {
2018         return container_of0(h, struct cl_object_header, coh_lu);
2019 }
2020
2021 static inline struct cl_site *cl_object_site(const struct cl_object *obj)
2022 {
2023         return lu2cl_site(obj->co_lu.lo_dev->ld_site);
2024 }
2025
2026 static inline
2027 struct cl_object_header *cl_object_header(const struct cl_object *obj)
2028 {
2029         return luh2coh(obj->co_lu.lo_header);
2030 }
2031
2032 static inline int cl_device_init(struct cl_device *d, struct lu_device_type *t)
2033 {
2034         return lu_device_init(&d->cd_lu_dev, t);
2035 }
2036
2037 static inline void cl_device_fini(struct cl_device *d)
2038 {
2039         lu_device_fini(&d->cd_lu_dev);
2040 }
2041
2042 void cl_page_slice_add(struct cl_page *page, struct cl_page_slice *slice,
2043                        struct cl_object *obj, pgoff_t index,
2044                        const struct cl_page_operations *ops);
2045 void cl_lock_slice_add(struct cl_lock *lock, struct cl_lock_slice *slice,
2046                        struct cl_object *obj,
2047                        const struct cl_lock_operations *ops);
2048 void cl_io_slice_add(struct cl_io *io, struct cl_io_slice *slice,
2049                      struct cl_object *obj, const struct cl_io_operations *ops);
2050 /** @} helpers */
2051
2052 /** \defgroup cl_object cl_object
2053  * @{ */
2054 struct cl_object *cl_object_top (struct cl_object *o);
2055 struct cl_object *cl_object_find(const struct lu_env *env, struct cl_device *cd,
2056                                  const struct lu_fid *fid,
2057                                  const struct cl_object_conf *c);
2058
2059 int  cl_object_header_init(struct cl_object_header *h);
2060 void cl_object_header_fini(struct cl_object_header *h);
2061 void cl_object_put        (const struct lu_env *env, struct cl_object *o);
2062 void cl_object_get        (struct cl_object *o);
2063 void cl_object_attr_lock  (struct cl_object *o);
2064 void cl_object_attr_unlock(struct cl_object *o);
2065 int  cl_object_attr_get(const struct lu_env *env, struct cl_object *obj,
2066                         struct cl_attr *attr);
2067 int  cl_object_attr_update(const struct lu_env *env, struct cl_object *obj,
2068                            const struct cl_attr *attr, unsigned valid);
2069 int  cl_object_glimpse    (const struct lu_env *env, struct cl_object *obj,
2070                            struct ost_lvb *lvb);
2071 int  cl_conf_set          (const struct lu_env *env, struct cl_object *obj,
2072                            const struct cl_object_conf *conf);
2073 int  cl_object_prune      (const struct lu_env *env, struct cl_object *obj);
2074 void cl_object_kill       (const struct lu_env *env, struct cl_object *obj);
2075 int cl_object_getstripe(const struct lu_env *env, struct cl_object *obj,
2076                         struct lov_user_md __user *lum, size_t size);
2077 int cl_object_fiemap(const struct lu_env *env, struct cl_object *obj,
2078                      struct ll_fiemap_info_key *fmkey, struct fiemap *fiemap,
2079                      size_t *buflen);
2080 int cl_object_layout_get(const struct lu_env *env, struct cl_object *obj,
2081                          struct cl_layout *cl);
2082 loff_t cl_object_maxbytes(struct cl_object *obj);
2083
2084 /**
2085  * Returns true, iff \a o0 and \a o1 are slices of the same object.
2086  */
2087 static inline int cl_object_same(struct cl_object *o0, struct cl_object *o1)
2088 {
2089         return cl_object_header(o0) == cl_object_header(o1);
2090 }
2091
2092 static inline void cl_object_page_init(struct cl_object *clob, int size)
2093 {
2094         clob->co_slice_off = cl_object_header(clob)->coh_page_bufsize;
2095         cl_object_header(clob)->coh_page_bufsize += cfs_size_round(size);
2096         WARN_ON(cl_object_header(clob)->coh_page_bufsize > 512);
2097 }
2098
2099 static inline void *cl_object_page_slice(struct cl_object *clob,
2100                                          struct cl_page *page)
2101 {
2102         return (void *)((char *)page + clob->co_slice_off);
2103 }
2104
2105 /**
2106  * Return refcount of cl_object.
2107  */
2108 static inline int cl_object_refc(struct cl_object *clob)
2109 {
2110         struct lu_object_header *header = clob->co_lu.lo_header;
2111         return atomic_read(&header->loh_ref);
2112 }
2113
2114 /** @} cl_object */
2115
2116 /** \defgroup cl_page cl_page
2117  * @{ */
2118 enum {
2119         CLP_GANG_OKAY = 0,
2120         CLP_GANG_RESCHED,
2121         CLP_GANG_AGAIN,
2122         CLP_GANG_ABORT
2123 };
2124 /* callback of cl_page_gang_lookup() */
2125
2126 struct cl_page *cl_page_find        (const struct lu_env *env,
2127                                      struct cl_object *obj,
2128                                      pgoff_t idx, struct page *vmpage,
2129                                      enum cl_page_type type);
2130 struct cl_page *cl_page_alloc       (const struct lu_env *env,
2131                                      struct cl_object *o, pgoff_t ind,
2132                                      struct page *vmpage,
2133                                      enum cl_page_type type);
2134 void            cl_page_get         (struct cl_page *page);
2135 void            cl_page_put         (const struct lu_env *env,
2136                                      struct cl_page *page);
2137 void            cl_page_print       (const struct lu_env *env, void *cookie,
2138                                      lu_printer_t printer,
2139                                      const struct cl_page *pg);
2140 void            cl_page_header_print(const struct lu_env *env, void *cookie,
2141                                      lu_printer_t printer,
2142                                      const struct cl_page *pg);
2143 struct cl_page *cl_vmpage_page      (struct page *vmpage, struct cl_object *obj);
2144 struct cl_page *cl_page_top         (struct cl_page *page);
2145
2146 const struct cl_page_slice *cl_page_at(const struct cl_page *page,
2147                                        const struct lu_device_type *dtype);
2148
2149 /**
2150  * \name ownership
2151  *
2152  * Functions dealing with the ownership of page by io.
2153  */
2154 /** @{ */
2155
2156 int  cl_page_own        (const struct lu_env *env,
2157                          struct cl_io *io, struct cl_page *page);
2158 int  cl_page_own_try    (const struct lu_env *env,
2159                          struct cl_io *io, struct cl_page *page);
2160 void cl_page_assume     (const struct lu_env *env,
2161                          struct cl_io *io, struct cl_page *page);
2162 void cl_page_unassume   (const struct lu_env *env,
2163                          struct cl_io *io, struct cl_page *pg);
2164 void cl_page_disown     (const struct lu_env *env,
2165                          struct cl_io *io, struct cl_page *page);
2166 int  cl_page_is_owned   (const struct cl_page *pg, const struct cl_io *io);
2167
2168 /** @} ownership */
2169
2170 /**
2171  * \name transfer
2172  *
2173  * Functions dealing with the preparation of a page for a transfer, and
2174  * tracking transfer state.
2175  */
2176 /** @{ */
2177 int  cl_page_prep       (const struct lu_env *env, struct cl_io *io,
2178                          struct cl_page *pg, enum cl_req_type crt);
2179 void cl_page_completion (const struct lu_env *env,
2180                          struct cl_page *pg, enum cl_req_type crt, int ioret);
2181 int  cl_page_make_ready (const struct lu_env *env, struct cl_page *pg,
2182                          enum cl_req_type crt);
2183 int  cl_page_cache_add  (const struct lu_env *env, struct cl_io *io,
2184                          struct cl_page *pg, enum cl_req_type crt);
2185 void cl_page_clip       (const struct lu_env *env, struct cl_page *pg,
2186                          int from, int to);
2187 int  cl_page_cancel     (const struct lu_env *env, struct cl_page *page);
2188 int  cl_page_flush      (const struct lu_env *env, struct cl_io *io,
2189                          struct cl_page *pg);
2190
2191 /** @} transfer */
2192
2193
2194 /**
2195  * \name helper routines
2196  * Functions to discard, delete and export a cl_page.
2197  */
2198 /** @{ */
2199 void    cl_page_discard(const struct lu_env *env, struct cl_io *io,
2200                         struct cl_page *pg);
2201 void    cl_page_delete(const struct lu_env *env, struct cl_page *pg);
2202 int     cl_page_is_vmlocked(const struct lu_env *env,
2203                             const struct cl_page *pg);
2204 void    cl_page_export(const struct lu_env *env,
2205                        struct cl_page *pg, int uptodate);
2206 loff_t  cl_offset(const struct cl_object *obj, pgoff_t idx);
2207 pgoff_t cl_index(const struct cl_object *obj, loff_t offset);
2208 size_t  cl_page_size(const struct cl_object *obj);
2209
2210 void cl_lock_print(const struct lu_env *env, void *cookie,
2211                    lu_printer_t printer, const struct cl_lock *lock);
2212 void cl_lock_descr_print(const struct lu_env *env, void *cookie,
2213                          lu_printer_t printer,
2214                          const struct cl_lock_descr *descr);
2215 /* @} helper */
2216
2217 /**
2218  * Data structure managing a client's cached pages. A count of
2219  * "unstable" pages is maintained, and an LRU of clean pages is
2220  * maintained. "unstable" pages are pages pinned by the ptlrpc
2221  * layer for recovery purposes.
2222  */
2223 struct cl_client_cache {
2224         /**
2225          * # of client cache refcount
2226          * # of users (OSCs) + 2 (held by llite and lov)
2227          */
2228         atomic_t                ccc_users;
2229         /**
2230          * # of threads are doing shrinking
2231          */
2232         unsigned int            ccc_lru_shrinkers;
2233         /**
2234          * # of LRU entries available
2235          */
2236         atomic_long_t           ccc_lru_left;
2237         /**
2238          * List of entities(OSCs) for this LRU cache
2239          */
2240         struct list_head        ccc_lru;
2241         /**
2242          * Max # of LRU entries
2243          */
2244         unsigned long           ccc_lru_max;
2245         /**
2246          * Lock to protect ccc_lru list
2247          */
2248         spinlock_t              ccc_lru_lock;
2249         /**
2250          * Set if unstable check is enabled
2251          */
2252         unsigned int            ccc_unstable_check:1;
2253         /**
2254          * # of unstable pages for this mount point
2255          */
2256         atomic_long_t           ccc_unstable_nr;
2257         /**
2258          * Waitq for awaiting unstable pages to reach zero.
2259          * Used at umounting time and signaled on BRW commit
2260          */
2261         wait_queue_head_t       ccc_unstable_waitq;
2262 };
2263 /**
2264  * cl_cache functions
2265  */
2266 struct cl_client_cache *cl_cache_init(unsigned long lru_page_max);
2267 void cl_cache_incref(struct cl_client_cache *cache);
2268 void cl_cache_decref(struct cl_client_cache *cache);
2269
2270 /** @} cl_page */
2271
2272 /** \defgroup cl_lock cl_lock
2273  * @{ */
2274 int cl_lock_request(const struct lu_env *env, struct cl_io *io,
2275                     struct cl_lock *lock);
2276 int cl_lock_init(const struct lu_env *env, struct cl_lock *lock,
2277                  const struct cl_io *io);
2278 void cl_lock_fini(const struct lu_env *env, struct cl_lock *lock);
2279 const struct cl_lock_slice *cl_lock_at(const struct cl_lock *lock,
2280                                        const struct lu_device_type *dtype);
2281 void cl_lock_release(const struct lu_env *env, struct cl_lock *lock);
2282
2283 int cl_lock_enqueue(const struct lu_env *env, struct cl_io *io,
2284                     struct cl_lock *lock, struct cl_sync_io *anchor);
2285 void cl_lock_cancel(const struct lu_env *env, struct cl_lock *lock);
2286
2287 /** @} cl_lock */
2288
2289 /** \defgroup cl_io cl_io
2290  * @{ */
2291
2292 int   cl_io_init         (const struct lu_env *env, struct cl_io *io,
2293                           enum cl_io_type iot, struct cl_object *obj);
2294 int   cl_io_sub_init     (const struct lu_env *env, struct cl_io *io,
2295                           enum cl_io_type iot, struct cl_object *obj);
2296 int   cl_io_rw_init      (const struct lu_env *env, struct cl_io *io,
2297                           enum cl_io_type iot, loff_t pos, size_t count);
2298 int   cl_io_loop         (const struct lu_env *env, struct cl_io *io);
2299
2300 void  cl_io_fini         (const struct lu_env *env, struct cl_io *io);
2301 int   cl_io_iter_init    (const struct lu_env *env, struct cl_io *io);
2302 void  cl_io_iter_fini    (const struct lu_env *env, struct cl_io *io);
2303 int   cl_io_lock         (const struct lu_env *env, struct cl_io *io);
2304 void  cl_io_unlock       (const struct lu_env *env, struct cl_io *io);
2305 int   cl_io_start        (const struct lu_env *env, struct cl_io *io);
2306 void  cl_io_end          (const struct lu_env *env, struct cl_io *io);
2307 int   cl_io_lock_add     (const struct lu_env *env, struct cl_io *io,
2308                           struct cl_io_lock_link *link);
2309 int   cl_io_lock_alloc_add(const struct lu_env *env, struct cl_io *io,
2310                            struct cl_lock_descr *descr);
2311 int   cl_io_submit_rw    (const struct lu_env *env, struct cl_io *io,
2312                           enum cl_req_type iot, struct cl_2queue *queue);
2313 int   cl_io_submit_sync  (const struct lu_env *env, struct cl_io *io,
2314                           enum cl_req_type iot, struct cl_2queue *queue,
2315                           long timeout);
2316 int   cl_io_commit_async (const struct lu_env *env, struct cl_io *io,
2317                           struct cl_page_list *queue, int from, int to,
2318                           cl_commit_cbt cb);
2319 int   cl_io_read_ahead   (const struct lu_env *env, struct cl_io *io,
2320                           pgoff_t start, struct cl_read_ahead *ra);
2321 void  cl_io_rw_advance   (const struct lu_env *env, struct cl_io *io,
2322                           size_t nob);
2323 int   cl_io_cancel       (const struct lu_env *env, struct cl_io *io,
2324                           struct cl_page_list *queue);
2325
2326 /**
2327  * True, iff \a io is an O_APPEND write(2).
2328  */
2329 static inline int cl_io_is_append(const struct cl_io *io)
2330 {
2331         return io->ci_type == CIT_WRITE && io->u.ci_rw.rw_append;
2332 }
2333
2334 static inline int cl_io_is_sync_write(const struct cl_io *io)
2335 {
2336         return io->ci_type == CIT_WRITE && io->u.ci_rw.rw_sync;
2337 }
2338
2339 static inline int cl_io_is_mkwrite(const struct cl_io *io)
2340 {
2341         return io->ci_type == CIT_FAULT && io->u.ci_fault.ft_mkwrite;
2342 }
2343
2344 /**
2345  * True, iff \a io is a truncate(2).
2346  */
2347 static inline int cl_io_is_trunc(const struct cl_io *io)
2348 {
2349         return io->ci_type == CIT_SETATTR &&
2350                 (io->u.ci_setattr.sa_valid & ATTR_SIZE);
2351 }
2352
2353 struct cl_io *cl_io_top(struct cl_io *io);
2354
2355 void cl_io_print(const struct lu_env *env, void *cookie,
2356                  lu_printer_t printer, const struct cl_io *io);
2357
2358 #define CL_IO_SLICE_CLEAN(foo_io, base)                                 \
2359 do {                                                                    \
2360         typeof(foo_io) __foo_io = (foo_io);                             \
2361                                                                         \
2362         CLASSERT(offsetof(typeof(*__foo_io), base) == 0);               \
2363         memset(&__foo_io->base + 1, 0,                                  \
2364                (sizeof *__foo_io) - sizeof __foo_io->base);             \
2365 } while (0)
2366
2367 /** @} cl_io */
2368
2369 /** \defgroup cl_page_list cl_page_list
2370  * @{ */
2371
2372 /**
2373  * Last page in the page list.
2374  */
2375 static inline struct cl_page *cl_page_list_last(struct cl_page_list *plist)
2376 {
2377         LASSERT(plist->pl_nr > 0);
2378         return list_entry(plist->pl_pages.prev, struct cl_page, cp_batch);
2379 }
2380
2381 static inline struct cl_page *cl_page_list_first(struct cl_page_list *plist)
2382 {
2383         LASSERT(plist->pl_nr > 0);
2384         return list_entry(plist->pl_pages.next, struct cl_page, cp_batch);
2385 }
2386
2387 /**
2388  * Iterate over pages in a page list.
2389  */
2390 #define cl_page_list_for_each(page, list)                               \
2391         list_for_each_entry((page), &(list)->pl_pages, cp_batch)
2392
2393 /**
2394  * Iterate over pages in a page list, taking possible removals into account.
2395  */
2396 #define cl_page_list_for_each_safe(page, temp, list)                    \
2397         list_for_each_entry_safe((page), (temp), &(list)->pl_pages, cp_batch)
2398
2399 void cl_page_list_init   (struct cl_page_list *plist);
2400 void cl_page_list_add    (struct cl_page_list *plist, struct cl_page *page);
2401 void cl_page_list_move   (struct cl_page_list *dst, struct cl_page_list *src,
2402                           struct cl_page *page);
2403 void cl_page_list_move_head(struct cl_page_list *dst, struct cl_page_list *src,
2404                           struct cl_page *page);
2405 void cl_page_list_splice (struct cl_page_list *list,
2406                           struct cl_page_list *head);
2407 void cl_page_list_del    (const struct lu_env *env,
2408                           struct cl_page_list *plist, struct cl_page *page);
2409 void cl_page_list_disown (const struct lu_env *env,
2410                           struct cl_io *io, struct cl_page_list *plist);
2411 void cl_page_list_assume (const struct lu_env *env,
2412                           struct cl_io *io, struct cl_page_list *plist);
2413 void cl_page_list_discard(const struct lu_env *env,
2414                           struct cl_io *io, struct cl_page_list *plist);
2415 void cl_page_list_fini   (const struct lu_env *env, struct cl_page_list *plist);
2416
2417 void cl_2queue_init     (struct cl_2queue *queue);
2418 void cl_2queue_add      (struct cl_2queue *queue, struct cl_page *page);
2419 void cl_2queue_disown   (const struct lu_env *env,
2420                          struct cl_io *io, struct cl_2queue *queue);
2421 void cl_2queue_assume   (const struct lu_env *env,
2422                          struct cl_io *io, struct cl_2queue *queue);
2423 void cl_2queue_discard  (const struct lu_env *env,
2424                          struct cl_io *io, struct cl_2queue *queue);
2425 void cl_2queue_fini     (const struct lu_env *env, struct cl_2queue *queue);
2426 void cl_2queue_init_page(struct cl_2queue *queue, struct cl_page *page);
2427
2428 /** @} cl_page_list */
2429
2430 void cl_req_attr_set(const struct lu_env *env, struct cl_object *obj,
2431                      struct cl_req_attr *attr);
2432
2433 /** \defgroup cl_sync_io cl_sync_io
2434  * @{ */
2435
2436 /**
2437  * Anchor for synchronous transfer. This is allocated on a stack by thread
2438  * doing synchronous transfer, and a pointer to this structure is set up in
2439  * every page submitted for transfer. Transfer completion routine updates
2440  * anchor and wakes up waiting thread when transfer is complete.
2441  */
2442 struct cl_sync_io {
2443         /** number of pages yet to be transferred. */
2444         atomic_t                csi_sync_nr;
2445         /** error code. */
2446         int                     csi_sync_rc;
2447         /** barrier of destroy this structure */
2448         atomic_t                csi_barrier;
2449         /** completion to be signaled when transfer is complete. */
2450         wait_queue_head_t       csi_waitq;
2451         /** callback to invoke when this IO is finished */
2452         void                    (*csi_end_io)(const struct lu_env *,
2453                                               struct cl_sync_io *);
2454 };
2455
2456 void cl_sync_io_init(struct cl_sync_io *anchor, int nr,
2457                      void (*end)(const struct lu_env *, struct cl_sync_io *));
2458 int  cl_sync_io_wait(const struct lu_env *env, struct cl_sync_io *anchor,
2459                      long timeout);
2460 void cl_sync_io_note(const struct lu_env *env, struct cl_sync_io *anchor,
2461                      int ioret);
2462 void cl_sync_io_end(const struct lu_env *env, struct cl_sync_io *anchor);
2463
2464 /** @} cl_sync_io */
2465
2466 /** \defgroup cl_env cl_env
2467  *
2468  * lu_env handling for a client.
2469  *
2470  * lu_env is an environment within which lustre code executes. Its major part
2471  * is lu_context---a fast memory allocation mechanism that is used to conserve
2472  * precious kernel stack space. Originally lu_env was designed for a server,
2473  * where
2474  *
2475  *     - there is a (mostly) fixed number of threads, and
2476  *
2477  *     - call chains have no non-lustre portions inserted between lustre code.
2478  *
2479  * On a client both these assumtpion fails, because every user thread can
2480  * potentially execute lustre code as part of a system call, and lustre calls
2481  * into VFS or MM that call back into lustre.
2482  *
2483  * To deal with that, cl_env wrapper functions implement the following
2484  * optimizations:
2485  *
2486  *     - allocation and destruction of environment is amortized by caching no
2487  *     longer used environments instead of destroying them;
2488  *
2489  * \see lu_env, lu_context, lu_context_key
2490  * @{ */
2491
2492 struct lu_env *cl_env_get(__u16 *refcheck);
2493 struct lu_env *cl_env_alloc(__u16 *refcheck, __u32 tags);
2494 void cl_env_put(struct lu_env *env, __u16 *refcheck);
2495 unsigned cl_env_cache_purge(unsigned nr);
2496 struct lu_env *cl_env_percpu_get(void);
2497 void cl_env_percpu_put(struct lu_env *env);
2498
2499 /** @} cl_env */
2500
2501 /*
2502  * Misc
2503  */
2504 void cl_attr2lvb(struct ost_lvb *lvb, const struct cl_attr *attr);
2505 void cl_lvb2attr(struct cl_attr *attr, const struct ost_lvb *lvb);
2506
2507 struct cl_device *cl_type_setup(const struct lu_env *env, struct lu_site *site,
2508                                 struct lu_device_type *ldt,
2509                                 struct lu_device *next);
2510 /** @} clio */
2511
2512 int cl_global_init(void);
2513 void cl_global_fini(void);
2514
2515 #endif /* _LINUX_CL_OBJECT_H */