Whamcloud - gitweb
519ed39a353a1750eee9485d1afefcbbdac759b2
[fs/lustre-release.git] / lustre / osc / osc_cache.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2011 Whamcloud, Inc.
31  *
32  */
33 /*
34  * This file is part of Lustre, http://www.lustre.org/
35  * Lustre is a trademark of Sun Microsystems, Inc.
36  *
37  * osc cache management.
38  *
39  * Author: Jinshan Xiong <jinshan.xiong@whamcloud.com>
40  */
41
42 #define DEBUG_SUBSYSTEM S_OSC
43
44 #include "osc_cl_internal.h"
45 #include "osc_internal.h"
46
47 static int extent_debug; /* set it to be true for more debug */
48
49 static void osc_update_pending(struct osc_object *obj, int cmd, int delta);
50 static int osc_extent_wait(const struct lu_env *env, struct osc_extent *ext,
51                            int state);
52 static void osc_ap_completion(const struct lu_env *env, struct client_obd *cli,
53                               struct osc_async_page *oap, int sent, int rc);
54 static int osc_make_ready(const struct lu_env *env, struct osc_async_page *oap,
55                           int cmd);
56 static int osc_refresh_count(const struct lu_env *env,
57                              struct osc_async_page *oap, int cmd);
58 static int osc_io_unplug_async(const struct lu_env *env,
59                                struct client_obd *cli, struct osc_object *osc);
60 static void osc_free_grant(struct client_obd *cli, unsigned int nr_pages,
61                            unsigned int lost_grant);
62
63 static void osc_extent_tree_dump0(int level, struct osc_object *obj,
64                                   const char *func, int line);
65 #define osc_extent_tree_dump(lvl, obj) \
66         osc_extent_tree_dump0(lvl, obj, __func__, __LINE__)
67
68 /** \addtogroup osc
69  *  @{
70  */
71
72 /* ------------------ osc extent ------------------ */
73 static inline char *ext_flags(struct osc_extent *ext, char *flags)
74 {
75         char *buf = flags;
76         *buf++ = ext->oe_rw ? 'r' : 'w';
77         if (ext->oe_intree)
78                 *buf++ = 'i';
79         if (ext->oe_srvlock)
80                 *buf++ = 's';
81         if (ext->oe_hp)
82                 *buf++ = 'h';
83         if (ext->oe_urgent)
84                 *buf++ = 'u';
85         if (ext->oe_memalloc)
86                 *buf++ = 'm';
87         if (ext->oe_trunc_pending)
88                 *buf++ = 't';
89         if (ext->oe_fsync_wait)
90                 *buf++ = 'Y';
91         *buf = 0;
92         return flags;
93 }
94
95 static inline char list_empty_marker(cfs_list_t *list)
96 {
97         return cfs_list_empty(list) ? '-' : '+';
98 }
99
100 #define EXTSTR       "[%lu -> %lu/%lu]"
101 #define EXTPARA(ext) (ext)->oe_start, (ext)->oe_end, (ext)->oe_max_end
102
103 #define OSC_EXTENT_DUMP(lvl, extent, fmt, ...) do {                           \
104         struct osc_extent *__ext = (extent);                                  \
105         const char *__str[] = OES_STRINGS;                                    \
106         char __buf[16];                                                       \
107                                                                               \
108         CDEBUG(lvl,                                                           \
109                 "extent %p@{" EXTSTR ", "                                     \
110                 "[%d|%d|%c|%s|%s|%p], [%d|%d|%c|%c|%p|%u|%p]} " fmt,          \
111                 /* ----- extent part 0 ----- */                               \
112                 __ext, EXTPARA(__ext),                                        \
113                 /* ----- part 1 ----- */                                      \
114                 cfs_atomic_read(&__ext->oe_refc),                             \
115                 cfs_atomic_read(&__ext->oe_users),                            \
116                 list_empty_marker(&__ext->oe_link),                           \
117                 __str[__ext->oe_state], ext_flags(__ext, __buf),              \
118                 __ext->oe_obj,                                                \
119                 /* ----- part 2 ----- */                                      \
120                 __ext->oe_grants, __ext->oe_nr_pages,                         \
121                 list_empty_marker(&__ext->oe_pages),                          \
122                 cfs_waitq_active(&__ext->oe_waitq) ? '+' : '-',               \
123                 __ext->oe_osclock, __ext->oe_mppr, __ext->oe_owner,           \
124                 /* ----- part 4 ----- */                                      \
125                 ## __VA_ARGS__);                                              \
126 } while (0)
127
128 #undef EASSERTF
129 #define EASSERTF(expr, ext, fmt, args...) do {                          \
130         if (!(expr)) {                                                  \
131                 OSC_EXTENT_DUMP(D_ERROR, (ext), fmt, ##args);            \
132                 osc_extent_tree_dump(D_ERROR, (ext)->oe_obj);            \
133                 LASSERT(expr);                                          \
134         }                                                                    \
135 } while (0)
136
137 #undef EASSERT
138 #define EASSERT(expr, ext) EASSERTF(expr, ext, "\n")
139
140 static inline struct osc_extent *rb_extent(struct rb_node *n)
141 {
142         if (n == NULL)
143                 return NULL;
144
145         return container_of(n, struct osc_extent, oe_node);
146 }
147
148 static inline struct osc_extent *next_extent(struct osc_extent *ext)
149 {
150         if (ext == NULL)
151                 return NULL;
152
153         LASSERT(ext->oe_intree);
154         return rb_extent(rb_next(&ext->oe_node));
155 }
156
157 static inline struct osc_extent *prev_extent(struct osc_extent *ext)
158 {
159         if (ext == NULL)
160                 return NULL;
161
162         LASSERT(ext->oe_intree);
163         return rb_extent(rb_prev(&ext->oe_node));
164 }
165
166 static inline struct osc_extent *first_extent(struct osc_object *obj)
167 {
168         return rb_extent(rb_first(&obj->oo_root));
169 }
170
171 /* object must be locked by caller. */
172 static int osc_extent_sanity_check0(struct osc_extent *ext,
173                                     const char *func, const int line)
174 {
175         struct osc_object *obj = ext->oe_obj;
176         struct osc_async_page *oap;
177         int page_count;
178         int rc = 0;
179
180         if (!osc_object_is_locked(obj))
181                 GOTO(out, rc = 9);
182
183         if (ext->oe_state >= OES_STATE_MAX)
184                 GOTO(out, rc = 10);
185
186         if (cfs_atomic_read(&ext->oe_refc) <= 0)
187                 GOTO(out, rc = 20);
188
189         if (cfs_atomic_read(&ext->oe_refc) < cfs_atomic_read(&ext->oe_users))
190                 GOTO(out, rc = 30);
191
192         switch (ext->oe_state) {
193         case OES_INV:
194                 if (ext->oe_nr_pages > 0 || !cfs_list_empty(&ext->oe_pages))
195                         GOTO(out, rc = 35);
196                 GOTO(out, rc = 0);
197                 break;
198         case OES_ACTIVE:
199                 if (cfs_atomic_read(&ext->oe_users) == 0)
200                         GOTO(out, rc = 40);
201                 if (ext->oe_hp)
202                         GOTO(out, rc = 50);
203                 if (ext->oe_fsync_wait && !ext->oe_urgent)
204                         GOTO(out, rc = 55);
205                 break;
206         case OES_CACHE:
207                 if (ext->oe_grants == 0)
208                         GOTO(out, rc = 60);
209                 if (ext->oe_fsync_wait && !ext->oe_urgent && !ext->oe_hp)
210                         GOTO(out, rc = 65);
211         default:
212                 if (cfs_atomic_read(&ext->oe_users) > 0)
213                         GOTO(out, rc = 70);
214         }
215
216         if (ext->oe_max_end < ext->oe_end || ext->oe_end < ext->oe_start)
217                 GOTO(out, rc = 80);
218
219         if (ext->oe_osclock == NULL && ext->oe_grants > 0)
220                 GOTO(out, rc = 90);
221
222         if (ext->oe_osclock) {
223                 struct cl_lock_descr *descr;
224                 descr = &ext->oe_osclock->cll_descr;
225                 if (!(descr->cld_start <= ext->oe_start &&
226                       descr->cld_end >= ext->oe_max_end))
227                         GOTO(out, rc = 100);
228         }
229
230         if (ext->oe_nr_pages > ext->oe_mppr)
231                 GOTO(out, rc = 105);
232
233         /* Do not verify page list if extent is in RPC. This is because an
234          * in-RPC extent is supposed to be exclusively accessible w/o lock. */
235         if (ext->oe_state > OES_CACHE)
236                 GOTO(out, rc = 0);
237
238         if (!extent_debug)
239                 GOTO(out, rc = 0);
240
241         page_count = 0;
242         cfs_list_for_each_entry(oap, &ext->oe_pages, oap_pending_item) {
243                 pgoff_t index = oap2cl_page(oap)->cp_index;
244                 ++page_count;
245                 if (index > ext->oe_end || index < ext->oe_start)
246                         GOTO(out, rc = 110);
247         }
248         if (page_count != ext->oe_nr_pages)
249                 GOTO(out, rc = 120);
250
251 out:
252         if (rc != 0)
253                 OSC_EXTENT_DUMP(D_ERROR, ext,
254                                 "%s:%d sanity check %p failed with rc = %d\n",
255                                 func, line, ext, rc);
256         return rc;
257 }
258
259 #define sanity_check_nolock(ext) \
260         osc_extent_sanity_check0(ext, __func__, __LINE__)
261
262 #define sanity_check(ext) ({                                                   \
263         int __res;                                                             \
264         osc_object_lock((ext)->oe_obj);                                        \
265         __res = sanity_check_nolock(ext);                                      \
266         osc_object_unlock((ext)->oe_obj);                                      \
267         __res;                                                                 \
268 })
269
270
271 /**
272  * sanity check - to make sure there is no overlapped extent in the tree.
273  */
274 static int osc_extent_is_overlapped(struct osc_object *obj,
275                                     struct osc_extent *ext)
276 {
277         struct osc_extent *tmp;
278
279         LASSERT(osc_object_is_locked(obj));
280
281         if (!extent_debug)
282                 return 0;
283
284         for (tmp = first_extent(obj); tmp != NULL; tmp = next_extent(tmp)) {
285                 if (tmp == ext)
286                         continue;
287                 if (tmp->oe_end >= ext->oe_start &&
288                     tmp->oe_start <= ext->oe_end)
289                         return 1;
290         }
291         return 0;
292 }
293
294 static void osc_extent_state_set(struct osc_extent *ext, int state)
295 {
296         LASSERT(osc_object_is_locked(ext->oe_obj));
297         LASSERT(state >= OES_INV && state < OES_STATE_MAX);
298
299         /* Never try to sanity check a state changing extent :-) */
300         /* LASSERT(sanity_check_nolock(ext) == 0); */
301
302         /* TODO: validate the state machine */
303         ext->oe_state = state;
304         cfs_waitq_broadcast(&ext->oe_waitq);
305 }
306
307 static struct osc_extent *osc_extent_alloc(struct osc_object *obj)
308 {
309         struct osc_extent *ext;
310
311         OBD_SLAB_ALLOC_PTR_GFP(ext, osc_extent_kmem, CFS_ALLOC_STD);
312         if (ext == NULL)
313                 return NULL;
314
315         RB_CLEAR_NODE(&ext->oe_node);
316         ext->oe_obj = obj;
317         cfs_atomic_set(&ext->oe_refc, 1);
318         cfs_atomic_set(&ext->oe_users, 0);
319         CFS_INIT_LIST_HEAD(&ext->oe_link);
320         ext->oe_state = OES_INV;
321         CFS_INIT_LIST_HEAD(&ext->oe_pages);
322         cfs_waitq_init(&ext->oe_waitq);
323         ext->oe_osclock = NULL;
324
325         return ext;
326 }
327
328 static void osc_extent_free(struct osc_extent *ext)
329 {
330         OBD_SLAB_FREE_PTR(ext, osc_extent_kmem);
331 }
332
333 static struct osc_extent *osc_extent_get(struct osc_extent *ext)
334 {
335         LASSERT(cfs_atomic_read(&ext->oe_refc) >= 0);
336         cfs_atomic_inc(&ext->oe_refc);
337         return ext;
338 }
339
340 static void osc_extent_put(const struct lu_env *env, struct osc_extent *ext)
341 {
342         LASSERT(cfs_atomic_read(&ext->oe_refc) > 0);
343         if (cfs_atomic_dec_and_test(&ext->oe_refc)) {
344                 LASSERT(cfs_list_empty(&ext->oe_link));
345                 LASSERT(cfs_atomic_read(&ext->oe_users) == 0);
346                 LASSERT(ext->oe_state == OES_INV);
347                 LASSERT(!ext->oe_intree);
348
349                 if (ext->oe_osclock) {
350                         cl_lock_put(env, ext->oe_osclock);
351                         ext->oe_osclock = NULL;
352                 }
353                 osc_extent_free(ext);
354         }
355 }
356
357 /**
358  * osc_extent_put_trust() is a special version of osc_extent_put() when
359  * it's known that the caller is not the last user. This is to address the
360  * problem of lacking of lu_env ;-).
361  */
362 static void osc_extent_put_trust(struct osc_extent *ext)
363 {
364         LASSERT(cfs_atomic_read(&ext->oe_refc) > 1);
365         LASSERT(osc_object_is_locked(ext->oe_obj));
366         cfs_atomic_dec(&ext->oe_refc);
367 }
368
369 /**
370  * Return the extent which includes pgoff @index, or return the greatest
371  * previous extent in the tree.
372  */
373 static struct osc_extent *osc_extent_search(struct osc_object *obj,
374                                             pgoff_t index)
375 {
376         struct rb_node    *n = obj->oo_root.rb_node;
377         struct osc_extent *tmp, *p = NULL;
378
379         LASSERT(osc_object_is_locked(obj));
380         while (n != NULL) {
381                 tmp = rb_extent(n);
382                 if (index < tmp->oe_start) {
383                         n = n->rb_left;
384                 } else if (index > tmp->oe_end) {
385                         p = rb_extent(n);
386                         n = n->rb_right;
387                 } else {
388                         return tmp;
389                 }
390         }
391         return p;
392 }
393
394 /*
395  * Return the extent covering @index, otherwise return NULL.
396  * caller must have held object lock.
397  */
398 static struct osc_extent *osc_extent_lookup(struct osc_object *obj,
399                                             pgoff_t index)
400 {
401         struct osc_extent *ext;
402
403         ext = osc_extent_search(obj, index);
404         if (ext != NULL && ext->oe_start <= index && index <= ext->oe_end)
405                 return osc_extent_get(ext);
406         return NULL;
407 }
408
409 /* caller must have held object lock. */
410 static void osc_extent_insert(struct osc_object *obj, struct osc_extent *ext)
411 {
412         struct rb_node   **n      = &obj->oo_root.rb_node;
413         struct rb_node    *parent = NULL;
414         struct osc_extent *tmp;
415
416         LASSERT(ext->oe_intree == 0);
417         LASSERT(ext->oe_obj == obj);
418         LASSERT(osc_object_is_locked(obj));
419         while (*n != NULL) {
420                 tmp = rb_extent(*n);
421                 parent = *n;
422
423                 if (ext->oe_end < tmp->oe_start)
424                         n = &(*n)->rb_left;
425                 else if (ext->oe_start > tmp->oe_end)
426                         n = &(*n)->rb_right;
427                 else
428                         EASSERTF(0, tmp, EXTSTR, EXTPARA(ext));
429         }
430         rb_link_node(&ext->oe_node, parent, n);
431         rb_insert_color(&ext->oe_node, &obj->oo_root);
432         osc_extent_get(ext);
433         ext->oe_intree = 1;
434 }
435
436 /* caller must have held object lock. */
437 static void osc_extent_erase(struct osc_extent *ext)
438 {
439         struct osc_object *obj = ext->oe_obj;
440         LASSERT(osc_object_is_locked(obj));
441         if (ext->oe_intree) {
442                 rb_erase(&ext->oe_node, &obj->oo_root);
443                 ext->oe_intree = 0;
444                 /* rbtree held a refcount */
445                 osc_extent_put_trust(ext);
446         }
447 }
448
449 static struct osc_extent *osc_extent_hold(struct osc_extent *ext)
450 {
451         struct osc_object *obj = ext->oe_obj;
452
453         LASSERT(osc_object_is_locked(obj));
454         LASSERT(ext->oe_state == OES_ACTIVE || ext->oe_state == OES_CACHE);
455         if (ext->oe_state == OES_CACHE) {
456                 osc_extent_state_set(ext, OES_ACTIVE);
457                 osc_update_pending(obj, OBD_BRW_WRITE, -ext->oe_nr_pages);
458         }
459         cfs_atomic_inc(&ext->oe_users);
460         cfs_list_del_init(&ext->oe_link);
461         return osc_extent_get(ext);
462 }
463
464 static void __osc_extent_remove(struct osc_extent *ext)
465 {
466         LASSERT(osc_object_is_locked(ext->oe_obj));
467         LASSERT(cfs_list_empty(&ext->oe_pages));
468         osc_extent_erase(ext);
469         cfs_list_del_init(&ext->oe_link);
470         osc_extent_state_set(ext, OES_INV);
471         OSC_EXTENT_DUMP(D_CACHE, ext, "destroyed.\n");
472 }
473
474 static void osc_extent_remove(struct osc_extent *ext)
475 {
476         struct osc_object *obj = ext->oe_obj;
477
478         osc_object_lock(obj);
479         __osc_extent_remove(ext);
480         osc_object_unlock(obj);
481 }
482
483 /**
484  * This function is used to merge extents to get better performance. It checks
485  * if @cur and @victim are contiguous at chunk level.
486  */
487 static int osc_extent_merge(const struct lu_env *env, struct osc_extent *cur,
488                             struct osc_extent *victim)
489 {
490         struct osc_object *obj = cur->oe_obj;
491         pgoff_t chunk_start;
492         pgoff_t chunk_end;
493         int ppc_bits;
494
495         LASSERT(cur->oe_state == OES_CACHE);
496         LASSERT(osc_object_is_locked(obj));
497         if (victim == NULL)
498                 return -EINVAL;
499
500         if (victim->oe_state != OES_CACHE || victim->oe_fsync_wait)
501                 return -EBUSY;
502
503         if (cur->oe_max_end != victim->oe_max_end)
504                 return -ERANGE;
505
506         LASSERT(cur->oe_osclock == victim->oe_osclock);
507         ppc_bits = osc_cli(obj)->cl_chunkbits - CFS_PAGE_SHIFT;
508         chunk_start = cur->oe_start >> ppc_bits;
509         chunk_end   = cur->oe_end   >> ppc_bits;
510         if (chunk_start   != (victim->oe_end >> ppc_bits) + 1 &&
511             chunk_end + 1 != victim->oe_start >> ppc_bits)
512                 return -ERANGE;
513
514         OSC_EXTENT_DUMP(D_CACHE, victim, "will be merged by %p.\n", cur);
515
516         cur->oe_start     = min(cur->oe_start, victim->oe_start);
517         cur->oe_end       = max(cur->oe_end,   victim->oe_end);
518         cur->oe_grants   += victim->oe_grants;
519         cur->oe_nr_pages += victim->oe_nr_pages;
520         /* only the following bits are needed to merge */
521         cur->oe_urgent   |= victim->oe_urgent;
522         cur->oe_memalloc |= victim->oe_memalloc;
523         cfs_list_splice_init(&victim->oe_pages, &cur->oe_pages);
524         cfs_list_del_init(&victim->oe_link);
525         victim->oe_nr_pages = 0;
526
527         osc_extent_get(victim);
528         __osc_extent_remove(victim);
529         osc_extent_put(env, victim);
530
531         OSC_EXTENT_DUMP(D_CACHE, cur, "after merging %p.\n", victim);
532         return 0;
533 }
534
535 /**
536  * Drop user count of osc_extent, and unplug IO asynchronously.
537  */
538 int osc_extent_release(const struct lu_env *env, struct osc_extent *ext)
539 {
540         struct osc_object *obj = ext->oe_obj;
541         int rc = 0;
542         ENTRY;
543
544         LASSERT(cfs_atomic_read(&ext->oe_users) > 0);
545         LASSERT(sanity_check(ext) == 0);
546         LASSERT(ext->oe_grants > 0);
547
548         if (cfs_atomic_dec_and_lock(&ext->oe_users, &obj->oo_lock)) {
549                 LASSERT(ext->oe_state == OES_ACTIVE);
550                 if (ext->oe_trunc_pending) {
551                         /* a truncate process is waiting for this extent.
552                          * This may happen due to a race, check
553                          * osc_cache_truncate_start(). */
554                         osc_extent_state_set(ext, OES_TRUNC);
555                         ext->oe_trunc_pending = 0;
556                 } else {
557                         osc_extent_state_set(ext, OES_CACHE);
558                         osc_update_pending(obj, OBD_BRW_WRITE,
559                                            ext->oe_nr_pages);
560
561                         /* try to merge the previous and next extent. */
562                         osc_extent_merge(env, ext, prev_extent(ext));
563                         osc_extent_merge(env, ext, next_extent(ext));
564
565                         if (ext->oe_urgent)
566                                 cfs_list_move_tail(&ext->oe_link,
567                                                    &obj->oo_urgent_exts);
568                 }
569                 osc_object_unlock(obj);
570
571                 osc_io_unplug_async(env, osc_cli(obj), obj);
572         }
573         osc_extent_put(env, ext);
574         RETURN(rc);
575 }
576
577 static inline int overlapped(struct osc_extent *ex1, struct osc_extent *ex2)
578 {
579         return !(ex1->oe_end < ex2->oe_start || ex2->oe_end < ex1->oe_start);
580 }
581
582 /**
583  * Find or create an extent which includes @index, core function to manage
584  * extent tree.
585  */
586 struct osc_extent *osc_extent_find(const struct lu_env *env,
587                                    struct osc_object *obj, pgoff_t index,
588                                    int *grants)
589
590 {
591         struct client_obd *cli = osc_cli(obj);
592         struct cl_lock    *lock;
593         struct osc_extent *cur;
594         struct osc_extent *ext;
595         struct osc_extent *conflict = NULL;
596         struct osc_extent *found = NULL;
597         pgoff_t    chunk;
598         pgoff_t    max_end;
599         int        max_pages; /* max_pages_per_rpc */
600         int        chunksize;
601         int        ppc_bits; /* pages per chunk bits */
602         int        chunk_mask;
603         int        rc;
604         ENTRY;
605
606         cur = osc_extent_alloc(obj);
607         if (cur == NULL)
608                 RETURN(ERR_PTR(-ENOMEM));
609
610         lock = cl_lock_at_pgoff(env, osc2cl(obj), index, NULL, 1, 0);
611         LASSERT(lock != NULL);
612         LASSERT(lock->cll_descr.cld_mode >= CLM_WRITE);
613
614         LASSERT(cli->cl_chunkbits >= CFS_PAGE_SHIFT);
615         ppc_bits   = cli->cl_chunkbits - CFS_PAGE_SHIFT;
616         chunk_mask = ~((1 << ppc_bits) - 1);
617         chunksize  = 1 << cli->cl_chunkbits;
618         chunk      = index >> ppc_bits;
619
620         /* align end to rpc edge, rpc size may not be a power 2 integer. */
621         max_pages = cli->cl_max_pages_per_rpc;
622         LASSERT((max_pages & ~chunk_mask) == 0);
623         max_end = index - (index % max_pages) + max_pages - 1;
624         max_end = min_t(pgoff_t, max_end, lock->cll_descr.cld_end);
625
626         /* initialize new extent by parameters so far */
627         cur->oe_max_end = max_end;
628         cur->oe_start   = index & chunk_mask;
629         cur->oe_end     = ((index + ~chunk_mask + 1) & chunk_mask) - 1;
630         if (cur->oe_start < lock->cll_descr.cld_start)
631                 cur->oe_start = lock->cll_descr.cld_start;
632         if (cur->oe_end > max_end)
633                 cur->oe_end = max_end;
634         cur->oe_osclock = lock;
635         cur->oe_grants  = 0;
636         cur->oe_mppr    = max_pages;
637
638         /* grants has been allocated by caller */
639         LASSERTF(*grants >= chunksize + cli->cl_extent_tax,
640                  "%u/%u/%u.\n", *grants, chunksize, cli->cl_extent_tax);
641         LASSERTF((max_end - cur->oe_start) < max_pages, EXTSTR, EXTPARA(cur));
642
643 restart:
644         osc_object_lock(obj);
645         ext = osc_extent_search(obj, cur->oe_start);
646         if (ext == NULL)
647                 ext = first_extent(obj);
648         while (ext != NULL) {
649                 loff_t ext_chk_start = ext->oe_start >> ppc_bits;
650                 loff_t ext_chk_end   = ext->oe_end   >> ppc_bits;
651
652                 LASSERT(sanity_check_nolock(ext) == 0);
653                 if (chunk > ext_chk_end + 1)
654                         break;
655
656                 /* if covering by different locks, no chance to match */
657                 if (lock != ext->oe_osclock) {
658                         EASSERTF(!overlapped(ext, cur), ext,
659                                  EXTSTR, EXTPARA(cur));
660
661                         ext = next_extent(ext);
662                         continue;
663                 }
664
665                 /* discontiguous chunks? */
666                 if (chunk + 1 < ext_chk_start) {
667                         ext = next_extent(ext);
668                         continue;
669                 }
670
671                 /* ok, from now on, ext and cur have these attrs:
672                  * 1. covered by the same lock
673                  * 2. contiguous at chunk level or overlapping. */
674
675                 if (overlapped(ext, cur)) {
676                         /* cur is the minimum unit, so overlapping means
677                          * full contain. */
678                         EASSERTF((ext->oe_start <= cur->oe_start &&
679                                   ext->oe_end >= cur->oe_end),
680                                  ext, EXTSTR, EXTPARA(cur));
681
682                         if (ext->oe_state > OES_CACHE || ext->oe_fsync_wait) {
683                                 /* for simplicity, we wait for this extent to
684                                  * finish before going forward. */
685                                 conflict = osc_extent_get(ext);
686                                 break;
687                         }
688
689                         found = osc_extent_hold(ext);
690                         break;
691                 }
692
693                 /* non-overlapped extent */
694                 if (ext->oe_state != OES_CACHE || ext->oe_fsync_wait) {
695                         /* we can't do anything for a non OES_CACHE extent, or
696                          * if there is someone waiting for this extent to be
697                          * flushed, try next one. */
698                         ext = next_extent(ext);
699                         continue;
700                 }
701
702                 /* check if they belong to the same rpc slot before trying to
703                  * merge. the extents are not overlapped and contiguous at
704                  * chunk level to get here. */
705                 if (ext->oe_max_end != max_end) {
706                         /* if they don't belong to the same RPC slot or
707                          * max_pages_per_rpc has ever changed, do not merge. */
708                         ext = next_extent(ext);
709                         continue;
710                 }
711
712                 /* it's required that an extent must be contiguous at chunk
713                  * level so that we know the whole extent is covered by grant
714                  * (the pages in the extent are NOT required to be contiguous).
715                  * Otherwise, it will be too much difficult to know which
716                  * chunks have grants allocated. */
717
718                 /* try to do front merge - extend ext's start */
719                 if (chunk + 1 == ext_chk_start) {
720                         /* ext must be chunk size aligned */
721                         EASSERT((ext->oe_start & ~chunk_mask) == 0, ext);
722
723                         /* pull ext's start back to cover cur */
724                         ext->oe_start   = cur->oe_start;
725                         ext->oe_grants += chunksize;
726                         *grants -= chunksize;
727
728                         found = osc_extent_hold(ext);
729                 } else if (chunk == ext_chk_end + 1) {
730                         /* rear merge */
731                         ext->oe_end     = cur->oe_end;
732                         ext->oe_grants += chunksize;
733                         *grants -= chunksize;
734
735                         /* try to merge with the next one because we just fill
736                          * in a gap */
737                         if (osc_extent_merge(env, ext, next_extent(ext)) == 0)
738                                 /* we can save extent tax from next extent */
739                                 *grants += cli->cl_extent_tax;
740
741                         found = osc_extent_hold(ext);
742                 }
743                 if (found != NULL)
744                         break;
745
746                 ext = next_extent(ext);
747         }
748
749         osc_extent_tree_dump(D_CACHE, obj);
750         if (found != NULL) {
751                 LASSERT(conflict == NULL);
752                 if (!IS_ERR(found)) {
753                         LASSERT(found->oe_osclock == cur->oe_osclock);
754                         OSC_EXTENT_DUMP(D_CACHE, found,
755                                         "found caching ext for %lu.\n", index);
756                 }
757         } else if (conflict == NULL) {
758                 /* create a new extent */
759                 EASSERT(osc_extent_is_overlapped(obj, cur) == 0, cur);
760                 cur->oe_grants = chunksize + cli->cl_extent_tax;
761                 *grants -= cur->oe_grants;
762                 LASSERT(*grants >= 0);
763
764                 cur->oe_state = OES_CACHE;
765                 found = osc_extent_hold(cur);
766                 osc_extent_insert(obj, cur);
767                 OSC_EXTENT_DUMP(D_CACHE, cur, "add into tree %lu/%lu.\n",
768                                 index, lock->cll_descr.cld_end);
769         }
770         osc_object_unlock(obj);
771
772         if (conflict != NULL) {
773                 LASSERT(found == NULL);
774
775                 /* waiting for IO to finish. Please notice that it's impossible
776                  * to be an OES_TRUNC extent. */
777                 rc = osc_extent_wait(env, conflict, OES_INV);
778                 osc_extent_put(env, conflict);
779                 conflict = NULL;
780                 if (rc < 0)
781                         GOTO(out, found = ERR_PTR(rc));
782
783                 goto restart;
784         }
785         EXIT;
786
787 out:
788         osc_extent_put(env, cur);
789         LASSERT(*grants >= 0);
790         return found;
791 }
792
793 /**
794  * Called when IO is finished to an extent.
795  */
796 int osc_extent_finish(const struct lu_env *env, struct osc_extent *ext,
797                       int sent, int rc)
798 {
799         struct client_obd *cli = osc_cli(ext->oe_obj);
800         struct osc_async_page *oap;
801         struct osc_async_page *tmp;
802         struct osc_async_page *last = NULL;
803         int nr_pages = ext->oe_nr_pages;
804         int lost_grant = 0;
805         int blocksize = cli->cl_import->imp_obd->obd_osfs.os_bsize ? : 4096;
806         ENTRY;
807
808         OSC_EXTENT_DUMP(D_CACHE, ext, "extent finished.\n");
809
810         ext->oe_rc = rc ?: ext->oe_nr_pages;
811         EASSERT(ergo(rc == 0, ext->oe_state == OES_RPC), ext);
812         cfs_list_for_each_entry_safe(oap, tmp, &ext->oe_pages,
813                                      oap_pending_item) {
814                 cfs_list_del_init(&oap->oap_rpc_item);
815                 cfs_list_del_init(&oap->oap_pending_item);
816                 if (last == NULL || last->oap_obj_off < oap->oap_obj_off)
817                         last = oap;
818
819                 --ext->oe_nr_pages;
820                 osc_ap_completion(env, cli, oap, sent, rc);
821         }
822         EASSERT(ext->oe_nr_pages == 0, ext);
823
824         if (!sent) {
825                 lost_grant = ext->oe_grants;
826         } else if (blocksize < CFS_PAGE_SIZE &&
827                    last->oap_count != CFS_PAGE_SIZE) {
828                 /* For short writes we shouldn't count parts of pages that
829                  * span a whole chunk on the OST side, or our accounting goes
830                  * wrong.  Should match the code in filter_grant_check. */
831                 int offset = oap->oap_page_off & ~CFS_PAGE_MASK;
832                 int count = oap->oap_count + (offset & (blocksize - 1));
833                 int end = (offset + oap->oap_count) & (blocksize - 1);
834                 if (end)
835                         count += blocksize - end;
836
837                 lost_grant = CFS_PAGE_SIZE - count;
838         }
839         if (ext->oe_grants > 0)
840                 osc_free_grant(cli, nr_pages, lost_grant);
841
842         osc_extent_remove(ext);
843         /* put the refcount for RPC */
844         osc_extent_put(env, ext);
845         RETURN(0);
846 }
847
848 static int extent_wait_cb(struct osc_extent *ext, int state)
849 {
850         int ret;
851
852         osc_object_lock(ext->oe_obj);
853         ret = ext->oe_state == state;
854         osc_object_unlock(ext->oe_obj);
855
856         return ret;
857 }
858
859 /**
860  * Wait for the extent's state to become @state.
861  */
862 static int osc_extent_wait(const struct lu_env *env, struct osc_extent *ext,
863                            int state)
864 {
865         struct osc_object *obj = ext->oe_obj;
866         struct l_wait_info lwi = LWI_TIMEOUT_INTR(cfs_time_seconds(600), NULL,
867                                                   LWI_ON_SIGNAL_NOOP, NULL);
868         int rc = 0;
869         ENTRY;
870
871         osc_object_lock(obj);
872         LASSERT(sanity_check_nolock(ext) == 0);
873         /* `Kick' this extent only if the caller is waiting for it to be
874          * written out. */
875         if (state == OES_INV && !ext->oe_urgent && !ext->oe_hp) {
876                 if (ext->oe_state == OES_ACTIVE) {
877                         ext->oe_urgent = 1;
878                 } else if (ext->oe_state == OES_CACHE) {
879                         ext->oe_urgent = 1;
880                         osc_extent_hold(ext);
881                         rc = 1;
882                 }
883         }
884         osc_object_unlock(obj);
885         if (rc == 1)
886                 osc_extent_release(env, ext);
887
888         /* wait for the extent until its state becomes @state */
889         rc = l_wait_event(ext->oe_waitq, extent_wait_cb(ext, state), &lwi);
890         if (rc == -ETIMEDOUT) {
891                 OSC_EXTENT_DUMP(D_ERROR, ext,
892                         "%s: wait ext to %d timedout, recovery in progress?\n",
893                         osc_export(obj)->exp_obd->obd_name, state);
894
895                 lwi = LWI_INTR(LWI_ON_SIGNAL_NOOP, NULL);
896                 rc = l_wait_event(ext->oe_waitq, extent_wait_cb(ext, state),
897                                   &lwi);
898         }
899         if (rc == 0 && ext->oe_rc < 0)
900                 rc = ext->oe_rc;
901         RETURN(rc);
902 }
903
904 /**
905  * Discard pages with index greater than @size. If @ext is overlapped with
906  * @size, then partial truncate happens.
907  */
908 static int osc_extent_truncate(struct osc_extent *ext, pgoff_t trunc_index,
909                                 bool partial)
910 {
911         struct cl_env_nest     nest;
912         struct lu_env         *env;
913         struct cl_io          *io;
914         struct osc_object     *obj = ext->oe_obj;
915         struct client_obd     *cli = osc_cli(obj);
916         struct osc_async_page *oap;
917         struct osc_async_page *tmp;
918         int                    pages_in_chunk = 0;
919         int                    ppc_bits    = cli->cl_chunkbits - CFS_PAGE_SHIFT;
920         __u64                  trunc_chunk = trunc_index >> ppc_bits;
921         int                    grants   = 0;
922         int                    nr_pages = 0;
923         int                    rc       = 0;
924         ENTRY;
925
926         LASSERT(sanity_check(ext) == 0);
927         LASSERT(ext->oe_state == OES_TRUNC);
928         LASSERT(!ext->oe_urgent);
929
930         /* Request new lu_env.
931          * We can't use that env from osc_cache_truncate_start() because
932          * it's from lov_io_sub and not fully initialized. */
933         env = cl_env_nested_get(&nest);
934         io  = &osc_env_info(env)->oti_io;
935         io->ci_obj = cl_object_top(osc2cl(obj));
936         rc = cl_io_init(env, io, CIT_MISC, io->ci_obj);
937         if (rc < 0)
938                 GOTO(out, rc);
939
940         /* discard all pages with index greater then trunc_index */
941         cfs_list_for_each_entry_safe(oap, tmp, &ext->oe_pages,
942                                      oap_pending_item) {
943                 struct cl_page  *sub  = oap2cl_page(oap);
944                 struct cl_page  *page = cl_page_top(sub);
945
946                 LASSERT(cfs_list_empty(&oap->oap_rpc_item));
947
948                 /* only discard the pages with their index greater than
949                  * trunc_index, and ... */
950                 if (sub->cp_index < trunc_index ||
951                     (sub->cp_index == trunc_index && partial)) {
952                         /* accounting how many pages remaining in the chunk
953                          * so that we can calculate grants correctly. */
954                         if (sub->cp_index >> ppc_bits == trunc_chunk)
955                                 ++pages_in_chunk;
956                         continue;
957                 }
958
959                 cfs_list_del_init(&oap->oap_pending_item);
960
961                 cl_page_get(page);
962                 lu_ref_add(&page->cp_reference, "truncate", cfs_current());
963
964                 if (cl_page_own(env, io, page) == 0) {
965                         cl_page_unmap(env, io, page);
966                         cl_page_discard(env, io, page);
967                         cl_page_disown(env, io, page);
968                 } else {
969                         LASSERT(page->cp_state == CPS_FREEING);
970                         LASSERT(0);
971                 }
972
973                 lu_ref_del(&page->cp_reference, "truncate", cfs_current());
974                 cl_page_put(env, page);
975
976                 --ext->oe_nr_pages;
977                 ++nr_pages;
978         }
979         EASSERTF(ergo(ext->oe_start >= trunc_index + !!partial,
980                       ext->oe_nr_pages == 0),
981                 ext, "trunc_index %lu, partial %d\n", trunc_index, partial);
982
983         osc_object_lock(obj);
984         if (ext->oe_nr_pages == 0) {
985                 LASSERT(pages_in_chunk == 0);
986                 grants = ext->oe_grants;
987                 ext->oe_grants = 0;
988         } else { /* calculate how many grants we can free */
989                 int     chunks = (ext->oe_end >> ppc_bits) - trunc_chunk;
990                 pgoff_t last_index;
991
992
993                 /* if there is no pages in this chunk, we can also free grants
994                  * for the last chunk */
995                 if (pages_in_chunk == 0) {
996                         /* if this is the 1st chunk and no pages in this chunk,
997                          * ext->oe_nr_pages must be zero, so we should be in
998                          * the other if-clause. */
999                         LASSERT(trunc_chunk > 0);
1000                         --trunc_chunk;
1001                         ++chunks;
1002                 }
1003
1004                 /* this is what we can free from this extent */
1005                 grants          = chunks << cli->cl_chunkbits;
1006                 ext->oe_grants -= grants;
1007                 last_index      = ((trunc_chunk + 1) << ppc_bits) - 1;
1008                 ext->oe_end     = min(last_index, ext->oe_max_end);
1009                 LASSERT(ext->oe_end >= ext->oe_start);
1010                 LASSERT(ext->oe_grants > 0);
1011         }
1012         osc_object_unlock(obj);
1013
1014         if (grants > 0 || nr_pages > 0)
1015                 osc_free_grant(cli, nr_pages, grants);
1016
1017 out:
1018         cl_io_fini(env, io);
1019         cl_env_nested_put(&nest, env);
1020         RETURN(rc);
1021 }
1022
1023 /**
1024  * This function is used to make the extent prepared for transfer.
1025  * A race with flusing page - ll_writepage() has to be handled cautiously.
1026  */
1027 static int osc_extent_make_ready(const struct lu_env *env,
1028                                  struct osc_extent *ext)
1029 {
1030         struct osc_async_page *oap;
1031         struct osc_async_page *last = NULL;
1032         struct osc_object *obj = ext->oe_obj;
1033         int page_count = 0;
1034         int rc;
1035         ENTRY;
1036
1037         /* we're going to grab page lock, so object lock must not be taken. */
1038         LASSERT(sanity_check(ext) == 0);
1039         /* in locking state, any process should not touch this extent. */
1040         EASSERT(ext->oe_state == OES_LOCKING, ext);
1041         EASSERT(ext->oe_owner != NULL, ext);
1042
1043         OSC_EXTENT_DUMP(D_CACHE, ext, "make ready\n");
1044
1045         cfs_list_for_each_entry(oap, &ext->oe_pages, oap_pending_item) {
1046                 ++page_count;
1047                 if (last == NULL || last->oap_obj_off < oap->oap_obj_off)
1048                         last = oap;
1049
1050                 /* checking ASYNC_READY is race safe */
1051                 if ((oap->oap_async_flags & ASYNC_READY) != 0)
1052                         continue;
1053
1054                 rc = osc_make_ready(env, oap, OBD_BRW_WRITE);
1055                 switch (rc) {
1056                 case 0:
1057                         cfs_spin_lock(&oap->oap_lock);
1058                         oap->oap_async_flags |= ASYNC_READY;
1059                         cfs_spin_unlock(&oap->oap_lock);
1060                         break;
1061                 case -EALREADY:
1062                         LASSERT((oap->oap_async_flags & ASYNC_READY) != 0);
1063                         break;
1064                 default:
1065                         LASSERTF(0, "unknown return code: %d\n", rc);
1066                 }
1067         }
1068
1069         LASSERT(page_count == ext->oe_nr_pages);
1070         LASSERT(last != NULL);
1071         /* the last page is the only one we need to refresh its count by
1072          * the size of file. */
1073         if (!(last->oap_async_flags & ASYNC_COUNT_STABLE)) {
1074                 last->oap_count = osc_refresh_count(env, last, OBD_BRW_WRITE);
1075                 LASSERT(last->oap_count > 0);
1076                 LASSERT(last->oap_page_off + last->oap_count <= CFS_PAGE_SIZE);
1077                 last->oap_async_flags |= ASYNC_COUNT_STABLE;
1078         }
1079
1080         /* for the rest of pages, we don't need to call osf_refresh_count()
1081          * because it's known they are not the last page */
1082         cfs_list_for_each_entry(oap, &ext->oe_pages, oap_pending_item) {
1083                 if (!(oap->oap_async_flags & ASYNC_COUNT_STABLE)) {
1084                         oap->oap_count = CFS_PAGE_SIZE - oap->oap_page_off;
1085                         oap->oap_async_flags |= ASYNC_COUNT_STABLE;
1086                 }
1087         }
1088
1089         osc_object_lock(obj);
1090         osc_extent_state_set(ext, OES_RPC);
1091         osc_object_unlock(obj);
1092         /* get a refcount for RPC. */
1093         osc_extent_get(ext);
1094
1095         RETURN(0);
1096 }
1097
1098 /**
1099  * Quick and simple version of osc_extent_find(). This function is frequently
1100  * called to expand the extent for the same IO. To expand the extent, the
1101  * page index must be in the same or next chunk of ext->oe_end.
1102  */
1103 static int osc_extent_expand(struct osc_extent *ext, pgoff_t index, int *grants)
1104 {
1105         struct osc_object *obj = ext->oe_obj;
1106         struct client_obd *cli = osc_cli(obj);
1107         struct osc_extent *next;
1108         int ppc_bits = cli->cl_chunkbits - CFS_PAGE_SHIFT;
1109         pgoff_t chunk = index >> ppc_bits;
1110         pgoff_t end_chunk;
1111         pgoff_t end_index;
1112         int chunksize = 1 << cli->cl_chunkbits;
1113         int rc = 0;
1114         ENTRY;
1115
1116         LASSERT(ext->oe_max_end >= index && ext->oe_start <= index);
1117         osc_object_lock(obj);
1118         LASSERT(sanity_check_nolock(ext) == 0);
1119         end_chunk = ext->oe_end >> ppc_bits;
1120         if (chunk > end_chunk + 1)
1121                 GOTO(out, rc = -ERANGE);
1122
1123         if (end_chunk >= chunk)
1124                 GOTO(out, rc = 0);
1125
1126         LASSERT(end_chunk + 1 == chunk);
1127         /* try to expand this extent to cover @index */
1128         end_index = min(ext->oe_max_end, ((chunk + 1) << ppc_bits) - 1);
1129
1130         next = next_extent(ext);
1131         if (next != NULL && next->oe_start <= end_index)
1132                 /* complex mode - overlapped with the next extent,
1133                  * this case will be handled by osc_extent_find() */
1134                 GOTO(out, rc = -EAGAIN);
1135
1136         ext->oe_end = end_index;
1137         ext->oe_grants += chunksize;
1138         *grants -= chunksize;
1139         LASSERT(*grants >= 0);
1140         EASSERTF(osc_extent_is_overlapped(obj, ext) == 0, ext,
1141                  "overlapped after expanding for %lu.\n", index);
1142         EXIT;
1143
1144 out:
1145         osc_object_unlock(obj);
1146         RETURN(rc);
1147 }
1148
1149 static void osc_extent_tree_dump0(int level, struct osc_object *obj,
1150                                   const char *func, int line)
1151 {
1152         struct osc_extent *ext;
1153         int cnt;
1154
1155         CDEBUG(level, "Dump object %p extents at %s:%d, mppr: %u.\n",
1156                obj, func, line, osc_cli(obj)->cl_max_pages_per_rpc);
1157
1158         /* osc_object_lock(obj); */
1159         cnt = 1;
1160         for (ext = first_extent(obj); ext != NULL; ext = next_extent(ext))
1161                 OSC_EXTENT_DUMP(level, ext, "in tree %d.\n", cnt++);
1162
1163         cnt = 1;
1164         cfs_list_for_each_entry(ext, &obj->oo_hp_exts, oe_link)
1165                 OSC_EXTENT_DUMP(level, ext, "hp %d.\n", cnt++);
1166
1167         cnt = 1;
1168         cfs_list_for_each_entry(ext, &obj->oo_urgent_exts, oe_link)
1169                 OSC_EXTENT_DUMP(level, ext, "urgent %d.\n", cnt++);
1170
1171         cnt = 1;
1172         cfs_list_for_each_entry(ext, &obj->oo_reading_exts, oe_link)
1173                 OSC_EXTENT_DUMP(level, ext, "reading %d.\n", cnt++);
1174         /* osc_object_unlock(obj); */
1175 }
1176
1177 /* ------------------ osc extent end ------------------ */
1178
1179 static inline int osc_is_ready(struct osc_object *osc)
1180 {
1181         return !cfs_list_empty(&osc->oo_ready_item) ||
1182                !cfs_list_empty(&osc->oo_hp_ready_item);
1183 }
1184
1185 #define OSC_IO_DEBUG(OSC, STR, args...)                                        \
1186         CDEBUG(D_CACHE, "obj %p ready %d|%c|%c wr %d|%c|%c rd %d|%c " STR,     \
1187                (OSC), osc_is_ready(OSC),                                       \
1188                list_empty_marker(&(OSC)->oo_hp_ready_item),                    \
1189                list_empty_marker(&(OSC)->oo_ready_item),                       \
1190                cfs_atomic_read(&(OSC)->oo_nr_writes),                          \
1191                list_empty_marker(&(OSC)->oo_hp_exts),                          \
1192                list_empty_marker(&(OSC)->oo_urgent_exts),                      \
1193                cfs_atomic_read(&(OSC)->oo_nr_reads),                           \
1194                list_empty_marker(&(OSC)->oo_reading_exts),                     \
1195                ##args)
1196
1197 static int osc_make_ready(const struct lu_env *env, struct osc_async_page *oap,
1198                           int cmd)
1199 {
1200         struct osc_page *opg  = oap2osc_page(oap);
1201         struct cl_page  *page = cl_page_top(oap2cl_page(oap));
1202         int result;
1203
1204         LASSERT(cmd == OBD_BRW_WRITE); /* no cached reads */
1205
1206         ENTRY;
1207         result = cl_page_make_ready(env, page, CRT_WRITE);
1208         if (result == 0)
1209                 opg->ops_submit_time = cfs_time_current();
1210         RETURN(result);
1211 }
1212
1213 static int osc_refresh_count(const struct lu_env *env,
1214                              struct osc_async_page *oap, int cmd)
1215 {
1216         struct osc_page  *opg = oap2osc_page(oap);
1217         struct cl_page   *page = oap2cl_page(oap);
1218         struct cl_object *obj;
1219         struct cl_attr   *attr = &osc_env_info(env)->oti_attr;
1220
1221         int result;
1222         loff_t kms;
1223
1224         /* readpage queues with _COUNT_STABLE, shouldn't get here. */
1225         LASSERT(!(cmd & OBD_BRW_READ));
1226         LASSERT(opg != NULL);
1227         obj = opg->ops_cl.cpl_obj;
1228
1229         cl_object_attr_lock(obj);
1230         result = cl_object_attr_get(env, obj, attr);
1231         cl_object_attr_unlock(obj);
1232         if (result < 0)
1233                 return result;
1234         kms = attr->cat_kms;
1235         if (cl_offset(obj, page->cp_index) >= kms)
1236                 /* catch race with truncate */
1237                 return 0;
1238         else if (cl_offset(obj, page->cp_index + 1) > kms)
1239                 /* catch sub-page write at end of file */
1240                 return kms % CFS_PAGE_SIZE;
1241         else
1242                 return CFS_PAGE_SIZE;
1243 }
1244
1245 static int osc_completion(const struct lu_env *env, struct osc_async_page *oap,
1246                           int cmd, int rc)
1247 {
1248         struct osc_page   *opg  = oap2osc_page(oap);
1249         struct cl_page    *page = cl_page_top(oap2cl_page(oap));
1250         struct osc_object *obj  = cl2osc(opg->ops_cl.cpl_obj);
1251         enum cl_req_type   crt;
1252         int srvlock;
1253
1254         ENTRY;
1255
1256         cmd &= ~OBD_BRW_NOQUOTA;
1257         LASSERT(equi(page->cp_state == CPS_PAGEIN,  cmd == OBD_BRW_READ));
1258         LASSERT(equi(page->cp_state == CPS_PAGEOUT, cmd == OBD_BRW_WRITE));
1259         LASSERT(opg->ops_transfer_pinned);
1260
1261         /*
1262          * page->cp_req can be NULL if io submission failed before
1263          * cl_req was allocated.
1264          */
1265         if (page->cp_req != NULL)
1266                 cl_req_page_done(env, page);
1267         LASSERT(page->cp_req == NULL);
1268
1269         crt = cmd == OBD_BRW_READ ? CRT_READ : CRT_WRITE;
1270         /* Clear opg->ops_transfer_pinned before VM lock is released. */
1271         opg->ops_transfer_pinned = 0;
1272
1273         cfs_spin_lock(&obj->oo_seatbelt);
1274         LASSERT(opg->ops_submitter != NULL);
1275         LASSERT(!cfs_list_empty(&opg->ops_inflight));
1276         cfs_list_del_init(&opg->ops_inflight);
1277         opg->ops_submitter = NULL;
1278         cfs_spin_unlock(&obj->oo_seatbelt);
1279
1280         opg->ops_submit_time = 0;
1281         srvlock = oap->oap_brw_flags & OBD_BRW_SRVLOCK;
1282
1283         cl_page_completion(env, page, crt, rc);
1284
1285         /* statistic */
1286         if (rc == 0 && srvlock) {
1287                 struct lu_device *ld    = opg->ops_cl.cpl_obj->co_lu.lo_dev;
1288                 struct osc_stats *stats = &lu2osc_dev(ld)->od_stats;
1289                 int bytes = oap->oap_count;
1290
1291                 if (crt == CRT_READ)
1292                         stats->os_lockless_reads += bytes;
1293                 else
1294                         stats->os_lockless_writes += bytes;
1295         }
1296
1297         /*
1298          * This has to be the last operation with the page, as locks are
1299          * released in cl_page_completion() and nothing except for the
1300          * reference counter protects page from concurrent reclaim.
1301          */
1302         lu_ref_del(&page->cp_reference, "transfer", page);
1303         /*
1304          * As page->cp_obj is pinned by a reference from page->cp_req, it is
1305          * safe to call cl_page_put() without risking object destruction in a
1306          * non-blocking context.
1307          */
1308         cl_page_put(env, page);
1309         RETURN(0);
1310 }
1311
1312 #define OSC_DUMP_GRANT(cli, fmt, args...) do {                                \
1313         struct client_obd *__tmp = (cli);                                     \
1314         CDEBUG(D_CACHE, "%s: { dirty: %ld/%ld dirty_pages: %d/%d "            \
1315                "dropped: %ld avail: %ld, reserved: %ld, flight: %d } " fmt,   \
1316                __tmp->cl_import->imp_obd->obd_name,                           \
1317                __tmp->cl_dirty, __tmp->cl_dirty_max,                          \
1318                cfs_atomic_read(&obd_dirty_pages), obd_max_dirty_pages,        \
1319                __tmp->cl_lost_grant, __tmp->cl_avail_grant,                   \
1320                __tmp->cl_reserved_grant, __tmp->cl_w_in_flight, ##args);      \
1321 } while (0)
1322
1323 /* caller must hold loi_list_lock */
1324 static void osc_consume_write_grant(struct client_obd *cli,
1325                                     struct brw_page *pga)
1326 {
1327         LASSERT_SPIN_LOCKED(&cli->cl_loi_list_lock.lock);
1328         LASSERT(!(pga->flag & OBD_BRW_FROM_GRANT));
1329         cfs_atomic_inc(&obd_dirty_pages);
1330         cli->cl_dirty += CFS_PAGE_SIZE;
1331         pga->flag |= OBD_BRW_FROM_GRANT;
1332         CDEBUG(D_CACHE, "using %lu grant credits for brw %p page %p\n",
1333                CFS_PAGE_SIZE, pga, pga->pg);
1334         osc_update_next_shrink(cli);
1335 }
1336
1337 /* the companion to osc_consume_write_grant, called when a brw has completed.
1338  * must be called with the loi lock held. */
1339 static void osc_release_write_grant(struct client_obd *cli,
1340                                     struct brw_page *pga)
1341 {
1342         ENTRY;
1343
1344         LASSERT_SPIN_LOCKED(&cli->cl_loi_list_lock.lock);
1345         if (!(pga->flag & OBD_BRW_FROM_GRANT)) {
1346                 EXIT;
1347                 return;
1348         }
1349
1350         pga->flag &= ~OBD_BRW_FROM_GRANT;
1351         cfs_atomic_dec(&obd_dirty_pages);
1352         cli->cl_dirty -= CFS_PAGE_SIZE;
1353         if (pga->flag & OBD_BRW_NOCACHE) {
1354                 pga->flag &= ~OBD_BRW_NOCACHE;
1355                 cfs_atomic_dec(&obd_dirty_transit_pages);
1356                 cli->cl_dirty_transit -= CFS_PAGE_SIZE;
1357         }
1358         EXIT;
1359 }
1360
1361 /**
1362  * To avoid sleeping with object lock held, it's good for us allocate enough
1363  * grants before entering into critical section.
1364  *
1365  * client_obd_list_lock held by caller
1366  */
1367 static int osc_reserve_grant(struct client_obd *cli, unsigned int bytes)
1368 {
1369         int rc = -EDQUOT;
1370
1371         if (cli->cl_avail_grant >= bytes) {
1372                 cli->cl_avail_grant    -= bytes;
1373                 cli->cl_reserved_grant += bytes;
1374                 rc = 0;
1375         }
1376         return rc;
1377 }
1378
1379 static void __osc_unreserve_grant(struct client_obd *cli,
1380                                   unsigned int reserved, unsigned int unused)
1381 {
1382         /* it's quite normal for us to get more grant than reserved.
1383          * Thinking about a case that two extents merged by adding a new
1384          * chunk, we can save one extent tax. If extent tax is greater than
1385          * one chunk, we can save more grant by adding a new chunk */
1386         cli->cl_reserved_grant -= reserved;
1387         if (unused > reserved) {
1388                 cli->cl_avail_grant += reserved;
1389                 cli->cl_lost_grant  += unused - reserved;
1390         } else {
1391                 cli->cl_avail_grant += unused;
1392         }
1393         if (unused > 0)
1394                 osc_wake_cache_waiters(cli);
1395 }
1396
1397 void osc_unreserve_grant(struct client_obd *cli,
1398                          unsigned int reserved, unsigned int unused)
1399 {
1400         client_obd_list_lock(&cli->cl_loi_list_lock);
1401         __osc_unreserve_grant(cli, reserved, unused);
1402         client_obd_list_unlock(&cli->cl_loi_list_lock);
1403 }
1404
1405 /**
1406  * Free grant after IO is finished or canceled.
1407  *
1408  * @lost_grant is used to remember how many grants we have allocated but not
1409  * used, we should return these grants to OST. There're two cases where grants
1410  * can be lost:
1411  * 1. truncate;
1412  * 2. blocksize at OST is less than CFS_PAGE_SIZE and a partial page was
1413  *    written. In this case OST may use less chunks to serve this partial
1414  *    write. OSTs don't actually know the page size on the client side. so
1415  *    clients have to calculate lost grant by the blocksize on the OST.
1416  *    See filter_grant_check() for details.
1417  */
1418 static void osc_free_grant(struct client_obd *cli, unsigned int nr_pages,
1419                            unsigned int lost_grant)
1420 {
1421         int grant = (1 << cli->cl_chunkbits) + cli->cl_extent_tax;
1422
1423         client_obd_list_lock(&cli->cl_loi_list_lock);
1424         cfs_atomic_sub(nr_pages, &obd_dirty_pages);
1425         cli->cl_dirty -= nr_pages << CFS_PAGE_SHIFT;
1426         cli->cl_lost_grant += lost_grant;
1427         if (cli->cl_avail_grant < grant && cli->cl_lost_grant >= grant) {
1428                 /* borrow some grant from truncate to avoid the case that
1429                  * truncate uses up all avail grant */
1430                 cli->cl_lost_grant -= grant;
1431                 cli->cl_avail_grant += grant;
1432         }
1433         osc_wake_cache_waiters(cli);
1434         client_obd_list_unlock(&cli->cl_loi_list_lock);
1435         CDEBUG(D_CACHE, "lost %u grant: %lu avail: %lu dirty: %lu\n",
1436                lost_grant, cli->cl_lost_grant,
1437                cli->cl_avail_grant, cli->cl_dirty);
1438 }
1439
1440 /* The companion to osc_enter_cache(), called when @oap is no longer part of
1441  * the dirty accounting.  Writeback completes or truncate happens before
1442  * writing starts.  Must be called with the loi lock held. */
1443 static void osc_exit_cache(struct client_obd *cli, struct osc_async_page *oap)
1444 {
1445         osc_release_write_grant(cli, &oap->oap_brw_page);
1446 }
1447
1448 /**
1449  * Non-blocking version of osc_enter_cache() that consumes grant only when it
1450  * is available.
1451  */
1452 static int osc_enter_cache_try(struct client_obd *cli,
1453                                struct osc_async_page *oap,
1454                                int bytes, int transient)
1455 {
1456         int rc;
1457
1458         OSC_DUMP_GRANT(cli, "need:%d.\n", bytes);
1459
1460         rc = osc_reserve_grant(cli, bytes);
1461         if (rc < 0)
1462                 return 0;
1463
1464         if (cli->cl_dirty + CFS_PAGE_SIZE <= cli->cl_dirty_max &&
1465             cfs_atomic_read(&obd_dirty_pages) + 1 <= obd_max_dirty_pages) {
1466                 osc_consume_write_grant(cli, &oap->oap_brw_page);
1467                 if (transient) {
1468                         cli->cl_dirty_transit += CFS_PAGE_SIZE;
1469                         cfs_atomic_inc(&obd_dirty_transit_pages);
1470                         oap->oap_brw_flags |= OBD_BRW_NOCACHE;
1471                 }
1472                 rc = 1;
1473         } else {
1474                 __osc_unreserve_grant(cli, bytes, bytes);
1475                 rc = 0;
1476         }
1477         return rc;
1478 }
1479
1480 /* Caller must hold loi_list_lock - we drop/regain it if we need to wait for
1481  * grant or cache space. */
1482 static int osc_enter_cache(const struct lu_env *env, struct client_obd *cli,
1483                            struct osc_async_page *oap, int bytes)
1484 {
1485         struct osc_object *osc = oap->oap_obj;
1486         struct lov_oinfo  *loi = osc->oo_oinfo;
1487         struct osc_cache_waiter ocw;
1488         struct l_wait_info lwi = LWI_INTR(LWI_ON_SIGNAL_NOOP, NULL);
1489         int rc = -EDQUOT;
1490         ENTRY;
1491
1492         OSC_DUMP_GRANT(cli, "need:%d.\n", bytes);
1493
1494         client_obd_list_lock(&cli->cl_loi_list_lock);
1495
1496         /* force the caller to try sync io.  this can jump the list
1497          * of queued writes and create a discontiguous rpc stream */
1498         if (OBD_FAIL_CHECK(OBD_FAIL_OSC_NO_GRANT) ||
1499             cli->cl_dirty_max < CFS_PAGE_SIZE     ||
1500             cli->cl_ar.ar_force_sync || loi->loi_ar.ar_force_sync)
1501                 GOTO(out, rc = -EDQUOT);
1502
1503         /* Hopefully normal case - cache space and write credits available */
1504         if (osc_enter_cache_try(cli, oap, bytes, 0))
1505                 GOTO(out, rc = 0);
1506
1507         /* We can get here for two reasons: too many dirty pages in cache, or
1508          * run out of grants. In both cases we should write dirty pages out.
1509          * Adding a cache waiter will trigger urgent write-out no matter what
1510          * RPC size will be.
1511          * The exiting condition is no avail grants and no dirty pages caching,
1512          * that really means there is no space on the OST. */
1513         cfs_waitq_init(&ocw.ocw_waitq);
1514         ocw.ocw_oap   = oap;
1515         ocw.ocw_grant = bytes;
1516         while (cli->cl_dirty > 0 || cli->cl_w_in_flight > 0) {
1517                 cfs_list_add_tail(&ocw.ocw_entry, &cli->cl_cache_waiters);
1518                 ocw.ocw_rc = 0;
1519                 client_obd_list_unlock(&cli->cl_loi_list_lock);
1520
1521                 osc_io_unplug(env, cli, osc, PDL_POLICY_ROUND);
1522
1523                 CDEBUG(D_CACHE, "%s: sleeping for cache space @ %p for %p\n",
1524                        cli->cl_import->imp_obd->obd_name, &ocw, oap);
1525
1526                 rc = l_wait_event(ocw.ocw_waitq,
1527                                   cfs_list_empty(&ocw.ocw_entry), &lwi);
1528
1529                 client_obd_list_lock(&cli->cl_loi_list_lock);
1530                 cfs_list_del_init(&ocw.ocw_entry);
1531                 if (rc < 0)
1532                         break;
1533
1534                 rc = ocw.ocw_rc;
1535                 if (rc != -EDQUOT)
1536                         break;
1537                 if (osc_enter_cache_try(cli, oap, bytes, 0)) {
1538                         rc = 0;
1539                         break;
1540                 }
1541         }
1542         EXIT;
1543
1544 out:
1545         client_obd_list_unlock(&cli->cl_loi_list_lock);
1546         OSC_DUMP_GRANT(cli, "returned %d.\n", rc);
1547         RETURN(rc);
1548 }
1549
1550 /* caller must hold loi_list_lock */
1551 void osc_wake_cache_waiters(struct client_obd *cli)
1552 {
1553         cfs_list_t *l, *tmp;
1554         struct osc_cache_waiter *ocw;
1555
1556         ENTRY;
1557         cfs_list_for_each_safe(l, tmp, &cli->cl_cache_waiters) {
1558                 /* if we can't dirty more, we must wait until some is written */
1559                 if ((cli->cl_dirty + CFS_PAGE_SIZE > cli->cl_dirty_max) ||
1560                     (cfs_atomic_read(&obd_dirty_pages) + 1 >
1561                      obd_max_dirty_pages)) {
1562                         CDEBUG(D_CACHE, "no dirty room: dirty: %ld "
1563                                "osc max %ld, sys max %d\n", cli->cl_dirty,
1564                                cli->cl_dirty_max, obd_max_dirty_pages);
1565                         return;
1566                 }
1567
1568                 /* if still dirty cache but no grant wait for pending RPCs that
1569                  * may yet return us some grant before doing sync writes */
1570                 if (cli->cl_w_in_flight && cli->cl_avail_grant < CFS_PAGE_SIZE) {
1571                         CDEBUG(D_CACHE, "%u BRW writes in flight, no grant\n",
1572                                cli->cl_w_in_flight);
1573                         return;
1574                 }
1575
1576                 ocw = cfs_list_entry(l, struct osc_cache_waiter, ocw_entry);
1577                 cfs_list_del_init(&ocw->ocw_entry);
1578
1579                 ocw->ocw_rc = 0;
1580                 if (!osc_enter_cache_try(cli, ocw->ocw_oap, ocw->ocw_grant, 0))
1581                         ocw->ocw_rc = -EDQUOT;
1582
1583                 CDEBUG(D_CACHE, "wake up %p for oap %p, avail grant %ld, %d\n",
1584                        ocw, ocw->ocw_oap, cli->cl_avail_grant, ocw->ocw_rc);
1585
1586                 cfs_waitq_signal(&ocw->ocw_waitq);
1587         }
1588
1589         EXIT;
1590 }
1591
1592 static int osc_max_rpc_in_flight(struct client_obd *cli, struct osc_object *osc)
1593 {
1594         int hprpc = !!cfs_list_empty(&osc->oo_hp_exts);
1595         return rpcs_in_flight(cli) >= cli->cl_max_rpcs_in_flight + hprpc;
1596 }
1597
1598 /* This maintains the lists of pending pages to read/write for a given object
1599  * (lop).  This is used by osc_check_rpcs->osc_next_obj() and osc_list_maint()
1600  * to quickly find objects that are ready to send an RPC. */
1601 static int osc_makes_rpc(struct client_obd *cli, struct osc_object *osc,
1602                          int cmd)
1603 {
1604         int invalid_import = 0;
1605         ENTRY;
1606
1607         /* if we have an invalid import we want to drain the queued pages
1608          * by forcing them through rpcs that immediately fail and complete
1609          * the pages.  recovery relies on this to empty the queued pages
1610          * before canceling the locks and evicting down the llite pages */
1611         if ((cli->cl_import == NULL || cli->cl_import->imp_invalid))
1612                 invalid_import = 1;
1613
1614         if (cmd & OBD_BRW_WRITE) {
1615                 if (cfs_atomic_read(&osc->oo_nr_writes) == 0)
1616                         RETURN(0);
1617                 if (invalid_import) {
1618                         CDEBUG(D_CACHE, "invalid import forcing RPC\n");
1619                         RETURN(1);
1620                 }
1621                 if (!cfs_list_empty(&osc->oo_hp_exts)) {
1622                         CDEBUG(D_CACHE, "high prio request forcing RPC\n");
1623                         RETURN(1);
1624                 }
1625                 if (!cfs_list_empty(&osc->oo_urgent_exts)) {
1626                         CDEBUG(D_CACHE, "urgent request forcing RPC\n");
1627                         RETURN(1);
1628                 }
1629                 /* trigger a write rpc stream as long as there are dirtiers
1630                  * waiting for space.  as they're waiting, they're not going to
1631                  * create more pages to coalesce with what's waiting.. */
1632                 if (!cfs_list_empty(&cli->cl_cache_waiters)) {
1633                         CDEBUG(D_CACHE, "cache waiters forcing RPC\n");
1634                         RETURN(1);
1635                 }
1636                 if (cfs_atomic_read(&osc->oo_nr_writes) >=
1637                     cli->cl_max_pages_per_rpc)
1638                         RETURN(1);
1639         } else {
1640                 if (cfs_atomic_read(&osc->oo_nr_reads) == 0)
1641                         RETURN(0);
1642                 if (invalid_import) {
1643                         CDEBUG(D_CACHE, "invalid import forcing RPC\n");
1644                         RETURN(1);
1645                 }
1646                 /* all read are urgent. */
1647                 if (!cfs_list_empty(&osc->oo_reading_exts))
1648                         RETURN(1);
1649         }
1650
1651         RETURN(0);
1652 }
1653
1654 static void osc_update_pending(struct osc_object *obj, int cmd, int delta)
1655 {
1656         struct client_obd *cli = osc_cli(obj);
1657         if (cmd & OBD_BRW_WRITE) {
1658                 cfs_atomic_add(delta, &obj->oo_nr_writes);
1659                 cfs_atomic_add(delta, &cli->cl_pending_w_pages);
1660                 LASSERT(cfs_atomic_read(&obj->oo_nr_writes) >= 0);
1661         } else {
1662                 cfs_atomic_add(delta, &obj->oo_nr_reads);
1663                 cfs_atomic_add(delta, &cli->cl_pending_r_pages);
1664                 LASSERT(cfs_atomic_read(&obj->oo_nr_reads) >= 0);
1665         }
1666         OSC_IO_DEBUG(obj, "update pending cmd %d delta %d.\n", cmd, delta);
1667 }
1668
1669 static int osc_makes_hprpc(struct osc_object *obj)
1670 {
1671         return !cfs_list_empty(&obj->oo_hp_exts);
1672 }
1673
1674 static void on_list(cfs_list_t *item, cfs_list_t *list, int should_be_on)
1675 {
1676         if (cfs_list_empty(item) && should_be_on)
1677                 cfs_list_add_tail(item, list);
1678         else if (!cfs_list_empty(item) && !should_be_on)
1679                 cfs_list_del_init(item);
1680 }
1681
1682 /* maintain the osc's cli list membership invariants so that osc_send_oap_rpc
1683  * can find pages to build into rpcs quickly */
1684 static int __osc_list_maint(struct client_obd *cli, struct osc_object *osc)
1685 {
1686         if (osc_makes_hprpc(osc)) {
1687                 /* HP rpc */
1688                 on_list(&osc->oo_ready_item, &cli->cl_loi_ready_list, 0);
1689                 on_list(&osc->oo_hp_ready_item, &cli->cl_loi_hp_ready_list, 1);
1690         } else {
1691                 on_list(&osc->oo_hp_ready_item, &cli->cl_loi_hp_ready_list, 0);
1692                 on_list(&osc->oo_ready_item, &cli->cl_loi_ready_list,
1693                         osc_makes_rpc(cli, osc, OBD_BRW_WRITE) ||
1694                         osc_makes_rpc(cli, osc, OBD_BRW_READ));
1695         }
1696
1697         on_list(&osc->oo_write_item, &cli->cl_loi_write_list,
1698                 cfs_atomic_read(&osc->oo_nr_writes) > 0);
1699
1700         on_list(&osc->oo_read_item, &cli->cl_loi_read_list,
1701                 cfs_atomic_read(&osc->oo_nr_reads) > 0);
1702
1703         return osc_is_ready(osc);
1704 }
1705
1706 static int osc_list_maint(struct client_obd *cli, struct osc_object *osc)
1707 {
1708         int is_ready;
1709
1710         client_obd_list_lock(&cli->cl_loi_list_lock);
1711         is_ready = __osc_list_maint(cli, osc);
1712         client_obd_list_unlock(&cli->cl_loi_list_lock);
1713
1714         return is_ready;
1715 }
1716
1717 /* this is trying to propogate async writeback errors back up to the
1718  * application.  As an async write fails we record the error code for later if
1719  * the app does an fsync.  As long as errors persist we force future rpcs to be
1720  * sync so that the app can get a sync error and break the cycle of queueing
1721  * pages for which writeback will fail. */
1722 static void osc_process_ar(struct osc_async_rc *ar, __u64 xid,
1723                            int rc)
1724 {
1725         if (rc) {
1726                 if (!ar->ar_rc)
1727                         ar->ar_rc = rc;
1728
1729                 ar->ar_force_sync = 1;
1730                 ar->ar_min_xid = ptlrpc_sample_next_xid();
1731                 return;
1732
1733         }
1734
1735         if (ar->ar_force_sync && (xid >= ar->ar_min_xid))
1736                 ar->ar_force_sync = 0;
1737 }
1738
1739 /* this must be called holding the loi list lock to give coverage to exit_cache,
1740  * async_flag maintenance, and oap_request */
1741 static void osc_ap_completion(const struct lu_env *env, struct client_obd *cli,
1742                               struct osc_async_page *oap, int sent, int rc)
1743 {
1744         struct osc_object *osc = oap->oap_obj;
1745         struct lov_oinfo  *loi = osc->oo_oinfo;
1746         __u64 xid = 0;
1747
1748         ENTRY;
1749         if (oap->oap_request != NULL) {
1750                 xid = ptlrpc_req_xid(oap->oap_request);
1751                 ptlrpc_req_finished(oap->oap_request);
1752                 oap->oap_request = NULL;
1753         }
1754
1755         /* As the transfer for this page is being done, clear the flags */
1756         cfs_spin_lock(&oap->oap_lock);
1757         oap->oap_async_flags = 0;
1758         cfs_spin_unlock(&oap->oap_lock);
1759         oap->oap_interrupted = 0;
1760
1761         if (oap->oap_cmd & OBD_BRW_WRITE && xid > 0) {
1762                 client_obd_list_lock(&cli->cl_loi_list_lock);
1763                 osc_process_ar(&cli->cl_ar, xid, rc);
1764                 osc_process_ar(&loi->loi_ar, xid, rc);
1765                 client_obd_list_unlock(&cli->cl_loi_list_lock);
1766         }
1767
1768         rc = osc_completion(env, oap, oap->oap_cmd, rc);
1769         if (rc)
1770                 CERROR("completion on oap %p obj %p returns %d.\n",
1771                        oap, osc, rc);
1772
1773         EXIT;
1774 }
1775
1776 /**
1777  * Try to add extent to one RPC. We need to think about the following things:
1778  * - # of pages must not be over max_pages_per_rpc
1779  * - extent must be compatible with previous ones
1780  */
1781 static int try_to_add_extent_for_io(struct client_obd *cli,
1782                                     struct osc_extent *ext, cfs_list_t *rpclist,
1783                                     int *pc, unsigned int *max_pages)
1784 {
1785         struct osc_extent *tmp;
1786         ENTRY;
1787
1788         EASSERT((ext->oe_state == OES_CACHE || ext->oe_state == OES_LOCK_DONE),
1789                 ext);
1790
1791         *max_pages = max(ext->oe_mppr, *max_pages);
1792         if (*pc + ext->oe_nr_pages > *max_pages)
1793                 RETURN(0);
1794
1795         cfs_list_for_each_entry(tmp, rpclist, oe_link) {
1796                 EASSERT(tmp->oe_owner == cfs_current(), tmp);
1797 #if 0
1798                 if (overlapped(tmp, ext)) {
1799                         OSC_EXTENT_DUMP(D_ERROR, tmp, "overlapped %p.\n", ext);
1800                         EASSERT(0, ext);
1801                 }
1802 #endif
1803
1804                 if (tmp->oe_srvlock != ext->oe_srvlock ||
1805                     !tmp->oe_grants != !ext->oe_grants)
1806                         RETURN(0);
1807
1808                 /* remove break for strict check */
1809                 break;
1810         }
1811
1812         *pc += ext->oe_nr_pages;
1813         cfs_list_move_tail(&ext->oe_link, rpclist);
1814         ext->oe_owner = cfs_current();
1815         RETURN(1);
1816 }
1817
1818 /**
1819  * In order to prevent multiple ptlrpcd from breaking contiguous extents,
1820  * get_write_extent() takes all appropriate extents in atomic.
1821  *
1822  * The following policy is used to collect extents for IO:
1823  * 1. Add as many HP extents as possible;
1824  * 2. Add the first urgent extent in urgent extent list and take it out of
1825  *    urgent list;
1826  * 3. Add subsequent extents of this urgent extent;
1827  * 4. If urgent list is not empty, goto 2;
1828  * 5. Traverse the extent tree from the 1st extent;
1829  * 6. Above steps exit if there is no space in this RPC.
1830  */
1831 static int get_write_extents(struct osc_object *obj, cfs_list_t *rpclist)
1832 {
1833         struct client_obd *cli = osc_cli(obj);
1834         struct osc_extent *ext;
1835         int page_count = 0;
1836         unsigned int max_pages = cli->cl_max_pages_per_rpc;
1837
1838         LASSERT(osc_object_is_locked(obj));
1839         while (!cfs_list_empty(&obj->oo_hp_exts)) {
1840                 ext = cfs_list_entry(obj->oo_hp_exts.next, struct osc_extent,
1841                                      oe_link);
1842                 LASSERT(ext->oe_state == OES_CACHE);
1843                 if (!try_to_add_extent_for_io(cli, ext, rpclist, &page_count,
1844                                               &max_pages))
1845                         return page_count;
1846                 EASSERT(ext->oe_nr_pages <= max_pages, ext);
1847         }
1848         if (page_count == max_pages)
1849                 return page_count;
1850
1851         while (!cfs_list_empty(&obj->oo_urgent_exts)) {
1852                 ext = cfs_list_entry(obj->oo_urgent_exts.next,
1853                                      struct osc_extent, oe_link);
1854                 if (!try_to_add_extent_for_io(cli, ext, rpclist, &page_count,
1855                                               &max_pages))
1856                         return page_count;
1857
1858                 if (!ext->oe_intree)
1859                         continue;
1860
1861                 while ((ext = next_extent(ext)) != NULL) {
1862                         if ((ext->oe_state != OES_CACHE) ||
1863                             (!cfs_list_empty(&ext->oe_link) &&
1864                              ext->oe_owner != NULL))
1865                                 continue;
1866
1867                         if (!try_to_add_extent_for_io(cli, ext, rpclist,
1868                                                       &page_count, &max_pages))
1869                                 return page_count;
1870                 }
1871         }
1872         if (page_count == max_pages)
1873                 return page_count;
1874
1875         ext = first_extent(obj);
1876         while (ext != NULL) {
1877                 if ((ext->oe_state != OES_CACHE) ||
1878                     /* this extent may be already in current rpclist */
1879                     (!cfs_list_empty(&ext->oe_link) && ext->oe_owner != NULL)) {
1880                         ext = next_extent(ext);
1881                         continue;
1882                 }
1883
1884                 if (!try_to_add_extent_for_io(cli, ext, rpclist, &page_count,
1885                                               &max_pages))
1886                         return page_count;
1887
1888                 ext = next_extent(ext);
1889         }
1890         return page_count;
1891 }
1892
1893 static int
1894 osc_send_write_rpc(const struct lu_env *env, struct client_obd *cli,
1895                    struct osc_object *osc, pdl_policy_t pol)
1896 {
1897         CFS_LIST_HEAD(rpclist);
1898         struct osc_extent *ext;
1899         struct osc_extent *tmp;
1900         struct osc_extent *first = NULL;
1901         obd_count page_count = 0;
1902         int srvlock = 0;
1903         int rc = 0;
1904         ENTRY;
1905
1906         LASSERT(osc_object_is_locked(osc));
1907
1908         page_count = get_write_extents(osc, &rpclist);
1909         LASSERT(equi(page_count == 0, cfs_list_empty(&rpclist)));
1910
1911         if (cfs_list_empty(&rpclist))
1912                 RETURN(0);
1913
1914         osc_update_pending(osc, OBD_BRW_WRITE, -page_count);
1915
1916         cfs_list_for_each_entry(ext, &rpclist, oe_link) {
1917                 LASSERT(ext->oe_state == OES_CACHE ||
1918                         ext->oe_state == OES_LOCK_DONE);
1919                 if (ext->oe_state == OES_CACHE)
1920                         osc_extent_state_set(ext, OES_LOCKING);
1921                 else
1922                         osc_extent_state_set(ext, OES_RPC);
1923         }
1924
1925         /* we're going to grab page lock, so release object lock because
1926          * lock order is page lock -> object lock. */
1927         osc_object_unlock(osc);
1928
1929         cfs_list_for_each_entry_safe(ext, tmp, &rpclist, oe_link) {
1930                 if (ext->oe_state == OES_LOCKING) {
1931                         rc = osc_extent_make_ready(env, ext);
1932                         if (unlikely(rc < 0)) {
1933                                 cfs_list_del_init(&ext->oe_link);
1934                                 osc_extent_finish(env, ext, 0, rc);
1935                                 continue;
1936                         }
1937                 }
1938                 if (first == NULL) {
1939                         first = ext;
1940                         srvlock = ext->oe_srvlock;
1941                 } else {
1942                         LASSERT(srvlock == ext->oe_srvlock);
1943                 }
1944         }
1945
1946         if (!cfs_list_empty(&rpclist)) {
1947                 LASSERT(page_count > 0);
1948                 rc = osc_build_rpc(env, cli, &rpclist, OBD_BRW_WRITE, pol);
1949                 LASSERT(cfs_list_empty(&rpclist));
1950         }
1951
1952         osc_object_lock(osc);
1953         RETURN(rc);
1954 }
1955
1956 /**
1957  * prepare pages for ASYNC io and put pages in send queue.
1958  *
1959  * \param cmd OBD_BRW_* macroses
1960  * \param lop pending pages
1961  *
1962  * \return zero if no page added to send queue.
1963  * \return 1 if pages successfully added to send queue.
1964  * \return negative on errors.
1965  */
1966 static int
1967 osc_send_read_rpc(const struct lu_env *env, struct client_obd *cli,
1968                   struct osc_object *osc, pdl_policy_t pol)
1969 {
1970         struct osc_extent *ext;
1971         struct osc_extent *next;
1972         CFS_LIST_HEAD(rpclist);
1973         int page_count = 0;
1974         unsigned int max_pages = cli->cl_max_pages_per_rpc;
1975         int rc = 0;
1976         ENTRY;
1977
1978         LASSERT(osc_object_is_locked(osc));
1979         cfs_list_for_each_entry_safe(ext, next,
1980                                      &osc->oo_reading_exts, oe_link) {
1981                 EASSERT(ext->oe_state == OES_LOCK_DONE, ext);
1982                 if (!try_to_add_extent_for_io(cli, ext, &rpclist, &page_count,
1983                                               &max_pages))
1984                         break;
1985                 osc_extent_state_set(ext, OES_RPC);
1986                 EASSERT(ext->oe_nr_pages <= max_pages, ext);
1987         }
1988         LASSERT(page_count <= max_pages);
1989
1990         osc_update_pending(osc, OBD_BRW_READ, -page_count);
1991
1992         if (!cfs_list_empty(&rpclist)) {
1993                 osc_object_unlock(osc);
1994
1995                 LASSERT(page_count > 0);
1996                 rc = osc_build_rpc(env, cli, &rpclist, OBD_BRW_READ, pol);
1997                 LASSERT(cfs_list_empty(&rpclist));
1998
1999                 osc_object_lock(osc);
2000         }
2001         RETURN(rc);
2002 }
2003
2004 #define list_to_obj(list, item) ({                                            \
2005         cfs_list_t *__tmp = (list)->next;                                     \
2006         cfs_list_del_init(__tmp);                                             \
2007         cfs_list_entry(__tmp, struct osc_object, oo_##item);                  \
2008 })
2009
2010 /* This is called by osc_check_rpcs() to find which objects have pages that
2011  * we could be sending.  These lists are maintained by osc_makes_rpc(). */
2012 static struct osc_object *osc_next_obj(struct client_obd *cli)
2013 {
2014         ENTRY;
2015
2016         /* First return objects that have blocked locks so that they
2017          * will be flushed quickly and other clients can get the lock,
2018          * then objects which have pages ready to be stuffed into RPCs */
2019         if (!cfs_list_empty(&cli->cl_loi_hp_ready_list))
2020                 RETURN(list_to_obj(&cli->cl_loi_hp_ready_list, hp_ready_item));
2021         if (!cfs_list_empty(&cli->cl_loi_ready_list))
2022                 RETURN(list_to_obj(&cli->cl_loi_ready_list, ready_item));
2023
2024         /* then if we have cache waiters, return all objects with queued
2025          * writes.  This is especially important when many small files
2026          * have filled up the cache and not been fired into rpcs because
2027          * they don't pass the nr_pending/object threshhold */
2028         if (!cfs_list_empty(&cli->cl_cache_waiters) &&
2029             !cfs_list_empty(&cli->cl_loi_write_list))
2030                 RETURN(list_to_obj(&cli->cl_loi_write_list, write_item));
2031
2032         /* then return all queued objects when we have an invalid import
2033          * so that they get flushed */
2034         if (cli->cl_import == NULL || cli->cl_import->imp_invalid) {
2035                 if (!cfs_list_empty(&cli->cl_loi_write_list))
2036                         RETURN(list_to_obj(&cli->cl_loi_write_list,
2037                                            write_item));
2038                 if (!cfs_list_empty(&cli->cl_loi_read_list))
2039                         RETURN(list_to_obj(&cli->cl_loi_read_list,
2040                                            read_item));
2041         }
2042         RETURN(NULL);
2043 }
2044
2045 /* called with the loi list lock held */
2046 static void osc_check_rpcs(const struct lu_env *env, struct client_obd *cli,
2047                            pdl_policy_t pol)
2048 {
2049         struct osc_object *osc;
2050         int rc = 0;
2051         ENTRY;
2052
2053         while ((osc = osc_next_obj(cli)) != NULL) {
2054                 struct cl_object *obj = osc2cl(osc);
2055                 struct lu_ref_link *link;
2056
2057                 OSC_IO_DEBUG(osc, "%lu in flight\n", rpcs_in_flight(cli));
2058
2059                 if (osc_max_rpc_in_flight(cli, osc)) {
2060                         __osc_list_maint(cli, osc);
2061                         break;
2062                 }
2063
2064                 cl_object_get(obj);
2065                 client_obd_list_unlock(&cli->cl_loi_list_lock);
2066                 link = lu_object_ref_add(&obj->co_lu, "check", cfs_current());
2067
2068                 /* attempt some read/write balancing by alternating between
2069                  * reads and writes in an object.  The makes_rpc checks here
2070                  * would be redundant if we were getting read/write work items
2071                  * instead of objects.  we don't want send_oap_rpc to drain a
2072                  * partial read pending queue when we're given this object to
2073                  * do io on writes while there are cache waiters */
2074                 osc_object_lock(osc);
2075                 if (osc_makes_rpc(cli, osc, OBD_BRW_WRITE)) {
2076                         rc = osc_send_write_rpc(env, cli, osc, pol);
2077                         if (rc < 0) {
2078                                 CERROR("Write request failed with %d\n", rc);
2079
2080                                 /* osc_send_write_rpc failed, mostly because of
2081                                  * memory pressure.
2082                                  *
2083                                  * It can't break here, because if:
2084                                  *  - a page was submitted by osc_io_submit, so
2085                                  *    page locked;
2086                                  *  - no request in flight
2087                                  *  - no subsequent request
2088                                  * The system will be in live-lock state,
2089                                  * because there is no chance to call
2090                                  * osc_io_unplug() and osc_check_rpcs() any
2091                                  * more. pdflush can't help in this case,
2092                                  * because it might be blocked at grabbing
2093                                  * the page lock as we mentioned.
2094                                  *
2095                                  * Anyway, continue to drain pages. */
2096                                 /* break; */
2097                         }
2098                 }
2099                 if (osc_makes_rpc(cli, osc, OBD_BRW_READ)) {
2100                         rc = osc_send_read_rpc(env, cli, osc, pol);
2101                         if (rc < 0)
2102                                 CERROR("Read request failed with %d\n", rc);
2103                 }
2104                 osc_object_unlock(osc);
2105
2106                 osc_list_maint(cli, osc);
2107                 lu_object_ref_del_at(&obj->co_lu, link, "check", cfs_current());
2108                 cl_object_put(env, obj);
2109
2110                 client_obd_list_lock(&cli->cl_loi_list_lock);
2111         }
2112 }
2113
2114 static int osc_io_unplug0(const struct lu_env *env, struct client_obd *cli,
2115                           struct osc_object *osc, pdl_policy_t pol, int async)
2116 {
2117         int has_rpcs = 1;
2118         int rc = 0;
2119
2120         client_obd_list_lock(&cli->cl_loi_list_lock);
2121         if (osc != NULL)
2122                 has_rpcs = __osc_list_maint(cli, osc);
2123         if (has_rpcs) {
2124                 if (!async) {
2125                         osc_check_rpcs(env, cli, pol);
2126                 } else {
2127                         CDEBUG(D_CACHE, "Queue writeback work for client %p.\n",
2128                                cli);
2129                         LASSERT(cli->cl_writeback_work != NULL);
2130                         rc = ptlrpcd_queue_work(cli->cl_writeback_work);
2131                 }
2132         }
2133         client_obd_list_unlock(&cli->cl_loi_list_lock);
2134         return rc;
2135 }
2136
2137 static int osc_io_unplug_async(const struct lu_env *env,
2138                                 struct client_obd *cli, struct osc_object *osc)
2139 {
2140         /* XXX: policy is no use actually. */
2141         return osc_io_unplug0(env, cli, osc, PDL_POLICY_ROUND, 1);
2142 }
2143
2144 void osc_io_unplug(const struct lu_env *env, struct client_obd *cli,
2145                    struct osc_object *osc, pdl_policy_t pol)
2146 {
2147         (void)osc_io_unplug0(env, cli, osc, pol, 0);
2148 }
2149
2150 int osc_prep_async_page(struct osc_object *osc, struct osc_page *ops,
2151                         cfs_page_t *page, loff_t offset)
2152 {
2153         struct obd_export     *exp = osc_export(osc);
2154         struct osc_async_page *oap = &ops->ops_oap;
2155         ENTRY;
2156
2157         if (!page)
2158                 return cfs_size_round(sizeof(*oap));
2159
2160         oap->oap_magic = OAP_MAGIC;
2161         oap->oap_cli = &exp->exp_obd->u.cli;
2162         oap->oap_obj = osc;
2163
2164         oap->oap_page = page;
2165         oap->oap_obj_off = offset;
2166         LASSERT(!(offset & ~CFS_PAGE_MASK));
2167
2168         if (!client_is_remote(exp) && cfs_capable(CFS_CAP_SYS_RESOURCE))
2169                 oap->oap_brw_flags = OBD_BRW_NOQUOTA;
2170
2171         CFS_INIT_LIST_HEAD(&oap->oap_pending_item);
2172         CFS_INIT_LIST_HEAD(&oap->oap_rpc_item);
2173
2174         cfs_spin_lock_init(&oap->oap_lock);
2175         CDEBUG(D_INFO, "oap %p page %p obj off "LPU64"\n",
2176                oap, page, oap->oap_obj_off);
2177         RETURN(0);
2178 }
2179
2180 int osc_queue_async_io(const struct lu_env *env, struct cl_io *io,
2181                        struct osc_page *ops)
2182 {
2183         struct osc_io *oio = osc_env_io(env);
2184         struct osc_extent     *ext = NULL;
2185         struct osc_async_page *oap = &ops->ops_oap;
2186         struct client_obd     *cli = oap->oap_cli;
2187         struct osc_object     *osc = oap->oap_obj;
2188         pgoff_t index;
2189         int    grants = 0;
2190         int    brw_flags = OBD_BRW_ASYNC;
2191         int    cmd = OBD_BRW_WRITE;
2192         int    need_release = 0;
2193         int    rc = 0;
2194         ENTRY;
2195
2196         if (oap->oap_magic != OAP_MAGIC)
2197                 RETURN(-EINVAL);
2198
2199         if (cli->cl_import == NULL || cli->cl_import->imp_invalid)
2200                 RETURN(-EIO);
2201
2202         if (!cfs_list_empty(&oap->oap_pending_item) ||
2203             !cfs_list_empty(&oap->oap_rpc_item))
2204                 RETURN(-EBUSY);
2205
2206         /* Set the OBD_BRW_SRVLOCK before the page is queued. */
2207         brw_flags |= ops->ops_srvlock ? OBD_BRW_SRVLOCK : 0;
2208         if (!client_is_remote(osc_export(osc)) &&
2209             cfs_capable(CFS_CAP_SYS_RESOURCE)) {
2210                 brw_flags |= OBD_BRW_NOQUOTA;
2211                 cmd |= OBD_BRW_NOQUOTA;
2212         }
2213
2214         /* check if the file's owner/group is over quota */
2215         if (!(cmd & OBD_BRW_NOQUOTA)) {
2216                 struct cl_object *obj;
2217                 struct cl_attr   *attr;
2218                 unsigned int qid[MAXQUOTAS];
2219
2220                 obj = cl_object_top(&osc->oo_cl);
2221                 attr = &osc_env_info(env)->oti_attr;
2222
2223                 cl_object_attr_lock(obj);
2224                 rc = cl_object_attr_get(env, obj, attr);
2225                 cl_object_attr_unlock(obj);
2226
2227                 qid[USRQUOTA] = attr->cat_uid;
2228                 qid[GRPQUOTA] = attr->cat_gid;
2229                 if (rc == 0 && osc_quota_chkdq(cli, qid) == NO_QUOTA)
2230                         rc = -EDQUOT;
2231                 if (rc)
2232                         RETURN(rc);
2233         }
2234
2235         oap->oap_cmd = cmd;
2236         oap->oap_page_off = ops->ops_from;
2237         oap->oap_count = ops->ops_to - ops->ops_from;
2238         oap->oap_async_flags = 0;
2239         oap->oap_brw_flags = brw_flags;
2240
2241         OSC_IO_DEBUG(osc, "oap %p page %p added for cmd %d\n",
2242                      oap, oap->oap_page, oap->oap_cmd & OBD_BRW_RWMASK);
2243
2244         index = oap2cl_page(oap)->cp_index;
2245
2246         /* Add this page into extent by the following steps:
2247          * 1. if there exists an active extent for this IO, mostly this page
2248          *    can be added to the active extent and sometimes we need to
2249          *    expand extent to accomodate this page;
2250          * 2. otherwise, a new extent will be allocated. */
2251
2252         ext = oio->oi_active;
2253         if (ext != NULL && ext->oe_start <= index && ext->oe_max_end >= index) {
2254                 /* one chunk plus extent overhead must be enough to write this
2255                  * page */
2256                 grants = (1 << cli->cl_chunkbits) + cli->cl_extent_tax;
2257                 if (ext->oe_end >= index)
2258                         grants = 0;
2259
2260                 /* it doesn't need any grant to dirty this page */
2261                 client_obd_list_lock(&cli->cl_loi_list_lock);
2262                 rc = osc_enter_cache_try(cli, oap, grants, 0);
2263                 client_obd_list_unlock(&cli->cl_loi_list_lock);
2264                 if (rc == 0) { /* try failed */
2265                         grants = 0;
2266                         need_release = 1;
2267                 } else if (ext->oe_end < index) {
2268                         int tmp = grants;
2269                         /* try to expand this extent */
2270                         rc = osc_extent_expand(ext, index, &tmp);
2271                         if (rc < 0) {
2272                                 need_release = 1;
2273                                 /* don't free reserved grant */
2274                         } else {
2275                                 OSC_EXTENT_DUMP(D_CACHE, ext,
2276                                                 "expanded for %lu.\n", index);
2277                                 osc_unreserve_grant(cli, grants, tmp);
2278                                 grants = 0;
2279                         }
2280                 }
2281                 rc = 0;
2282         } else if (ext != NULL) {
2283                 /* index is located outside of active extent */
2284                 need_release = 1;
2285         }
2286         if (need_release) {
2287                 osc_extent_release(env, ext);
2288                 oio->oi_active = NULL;
2289                 ext = NULL;
2290         }
2291
2292         if (ext == NULL) {
2293                 int tmp = (1 << cli->cl_chunkbits) + cli->cl_extent_tax;
2294
2295                 /* try to find new extent to cover this page */
2296                 LASSERT(oio->oi_active == NULL);
2297                 /* we may have allocated grant for this page if we failed
2298                  * to expand the previous active extent. */
2299                 LASSERT(ergo(grants > 0, grants >= tmp));
2300
2301                 rc = 0;
2302                 if (grants == 0) {
2303                         /* we haven't allocated grant for this page. */
2304                         rc = osc_enter_cache(env, cli, oap, tmp);
2305                         if (rc == 0)
2306                                 grants = tmp;
2307                 }
2308
2309                 tmp = grants;
2310                 if (rc == 0) {
2311                         ext = osc_extent_find(env, osc, index, &tmp);
2312                         if (IS_ERR(ext)) {
2313                                 LASSERT(tmp == grants);
2314                                 osc_exit_cache(cli, oap);
2315                                 rc = PTR_ERR(ext);
2316                                 ext = NULL;
2317                         } else {
2318                                 oio->oi_active = ext;
2319                         }
2320                 }
2321                 if (grants > 0)
2322                         osc_unreserve_grant(cli, grants, tmp);
2323         }
2324
2325         LASSERT(ergo(rc == 0, ext != NULL));
2326         if (ext != NULL) {
2327                 EASSERTF(ext->oe_end >= index && ext->oe_start <= index,
2328                          ext, "index = %lu.\n", index);
2329                 LASSERT((oap->oap_brw_flags & OBD_BRW_FROM_GRANT) != 0);
2330
2331                 osc_object_lock(osc);
2332                 if (ext->oe_nr_pages == 0)
2333                         ext->oe_srvlock = ops->ops_srvlock;
2334                 else
2335                         LASSERT(ext->oe_srvlock == ops->ops_srvlock);
2336                 ++ext->oe_nr_pages;
2337                 cfs_list_add_tail(&oap->oap_pending_item, &ext->oe_pages);
2338                 osc_object_unlock(osc);
2339         }
2340         RETURN(rc);
2341 }
2342
2343 int osc_teardown_async_page(const struct lu_env *env,
2344                             struct osc_object *obj, struct osc_page *ops)
2345 {
2346         struct osc_async_page *oap = &ops->ops_oap;
2347         struct osc_extent     *ext = NULL;
2348         int rc = 0;
2349         ENTRY;
2350
2351         LASSERT(oap->oap_magic == OAP_MAGIC);
2352
2353         CDEBUG(D_INFO, "teardown oap %p page %p at index %lu.\n",
2354                oap, ops, oap2cl_page(oap)->cp_index);
2355
2356         osc_object_lock(obj);
2357         if (!cfs_list_empty(&oap->oap_rpc_item)) {
2358                 CDEBUG(D_CACHE, "oap %p is not in cache.\n", oap);
2359                 rc = -EBUSY;
2360         } else if (!cfs_list_empty(&oap->oap_pending_item)) {
2361                 ext = osc_extent_lookup(obj, oap2cl_page(oap)->cp_index);
2362                 /* only truncated pages are allowed to be taken out.
2363                  * See osc_extent_truncate() and osc_cache_truncate_start()
2364                  * for details. */
2365                 if (ext != NULL && ext->oe_state != OES_TRUNC) {
2366                         OSC_EXTENT_DUMP(D_ERROR, ext, "trunc at %lu.\n",
2367                                         oap2cl_page(oap)->cp_index);
2368                         rc = -EBUSY;
2369                 }
2370         }
2371         osc_object_unlock(obj);
2372         if (ext != NULL)
2373                 osc_extent_put(env, ext);
2374         RETURN(rc);
2375 }
2376
2377 /**
2378  * This is called when a page is picked up by kernel to write out.
2379  *
2380  * We should find out the corresponding extent and add the whole extent
2381  * into urgent list. The extent may be being truncated or used, handle it
2382  * carefully.
2383  */
2384 int osc_flush_async_page(const struct lu_env *env, struct cl_io *io,
2385                          struct osc_page *ops)
2386 {
2387         struct osc_extent *ext   = NULL;
2388         struct osc_object *obj   = cl2osc(ops->ops_cl.cpl_obj);
2389         struct cl_page    *cp    = ops->ops_cl.cpl_page;
2390         pgoff_t            index = cp->cp_index;
2391         struct osc_async_page *oap = &ops->ops_oap;
2392         int unplug = 0;
2393         int rc = 0;
2394         ENTRY;
2395
2396         osc_object_lock(obj);
2397         ext = osc_extent_lookup(obj, index);
2398         if (ext == NULL) {
2399                 osc_extent_tree_dump(D_ERROR, obj);
2400                 LASSERTF(0, "page index %lu is NOT covered.\n", index);
2401         }
2402
2403         switch (ext->oe_state) {
2404         case OES_RPC:
2405         case OES_LOCK_DONE:
2406                 CL_PAGE_DEBUG(D_ERROR, env, cl_page_top(cp),
2407                               "flush an in-rpc page?\n");
2408                 LASSERT(0);
2409                 break;
2410         case OES_LOCKING:
2411                 /* If we know this extent is being written out, we should abort
2412                  * so that the writer can make this page ready. Otherwise, there
2413                  * exists a deadlock problem because other process can wait for
2414                  * page writeback bit holding page lock; and meanwhile in
2415                  * vvp_page_make_ready(), we need to grab page lock before
2416                  * really sending the RPC. */
2417         case OES_TRUNC:
2418                 /* race with truncate, page will be redirtied */
2419                 GOTO(out, rc = -EAGAIN);
2420         default:
2421                 break;
2422         }
2423
2424         rc = cl_page_prep(env, io, cl_page_top(cp), CRT_WRITE);
2425         if (rc)
2426                 GOTO(out, rc);
2427
2428         cfs_spin_lock(&oap->oap_lock);
2429         oap->oap_async_flags |= ASYNC_READY|ASYNC_URGENT;
2430         cfs_spin_unlock(&oap->oap_lock);
2431
2432         if (cfs_memory_pressure_get())
2433                 ext->oe_memalloc = 1;
2434
2435         ext->oe_urgent = 1;
2436         if (ext->oe_state == OES_CACHE && cfs_list_empty(&ext->oe_link)) {
2437                 OSC_EXTENT_DUMP(D_CACHE, ext,
2438                                 "flush page %p make it urgent.\n", oap);
2439                 cfs_list_add_tail(&ext->oe_link, &obj->oo_urgent_exts);
2440                 unplug = 1;
2441         }
2442         rc = 0;
2443         EXIT;
2444
2445 out:
2446         osc_object_unlock(obj);
2447         osc_extent_put(env, ext);
2448         if (unplug)
2449                 osc_io_unplug_async(env, osc_cli(obj), obj);
2450         return rc;
2451 }
2452
2453 /**
2454  * this is called when a sync waiter receives an interruption.  Its job is to
2455  * get the caller woken as soon as possible.  If its page hasn't been put in an
2456  * rpc yet it can dequeue immediately.  Otherwise it has to mark the rpc as
2457  * desiring interruption which will forcefully complete the rpc once the rpc
2458  * has timed out.
2459  */
2460 int osc_cancel_async_page(const struct lu_env *env, struct osc_page *ops)
2461 {
2462         struct osc_async_page *oap = &ops->ops_oap;
2463         struct osc_object     *obj = oap->oap_obj;
2464         struct client_obd     *cli = osc_cli(obj);
2465         struct osc_extent     *ext;
2466         struct osc_extent     *found = NULL;
2467         cfs_list_t            *plist;
2468         pgoff_t index = oap2cl_page(oap)->cp_index;
2469         int     rc = -EBUSY;
2470         int     cmd;
2471         ENTRY;
2472
2473         LASSERT(!oap->oap_interrupted);
2474         oap->oap_interrupted = 1;
2475
2476         /* Find out the caching extent */
2477         osc_object_lock(obj);
2478         if (oap->oap_cmd & OBD_BRW_WRITE) {
2479                 plist = &obj->oo_urgent_exts;
2480                 cmd   = OBD_BRW_WRITE;
2481         } else {
2482                 plist = &obj->oo_reading_exts;
2483                 cmd   = OBD_BRW_READ;
2484         }
2485         cfs_list_for_each_entry(ext, plist, oe_link) {
2486                 if (ext->oe_start <= index && ext->oe_end >= index) {
2487                         LASSERT(ext->oe_state == OES_LOCK_DONE);
2488                         /* For OES_LOCK_DONE state extent, it has already held
2489                          * a refcount for RPC. */
2490                         found = osc_extent_get(ext);
2491                         break;
2492                 }
2493         }
2494         if (found != NULL) {
2495                 cfs_list_del_init(&found->oe_link);
2496                 osc_update_pending(obj, cmd, -found->oe_nr_pages);
2497                 osc_object_unlock(obj);
2498
2499                 osc_extent_finish(env, found, 0, -EINTR);
2500                 osc_extent_put(env, found);
2501                 rc = 0;
2502         } else {
2503                 osc_object_unlock(obj);
2504                 /* ok, it's been put in an rpc. only one oap gets a request
2505                  * reference */
2506                 if (oap->oap_request != NULL) {
2507                         ptlrpc_mark_interrupted(oap->oap_request);
2508                         ptlrpcd_wake(oap->oap_request);
2509                         ptlrpc_req_finished(oap->oap_request);
2510                         oap->oap_request = NULL;
2511                 }
2512         }
2513
2514         osc_list_maint(cli, obj);
2515         RETURN(rc);
2516 }
2517
2518 int osc_queue_sync_pages(const struct lu_env *env, struct osc_object *obj,
2519                          cfs_list_t *list, int cmd, int brw_flags)
2520 {
2521         struct client_obd     *cli = osc_cli(obj);
2522         struct osc_extent     *ext;
2523         struct osc_async_page *oap;
2524         int     page_count = 0;
2525         int     mppr       = cli->cl_max_pages_per_rpc;
2526         pgoff_t start      = CL_PAGE_EOF;
2527         pgoff_t end        = 0;
2528         ENTRY;
2529
2530         cfs_list_for_each_entry(oap, list, oap_pending_item) {
2531                 struct cl_page *cp = oap2cl_page(oap);
2532                 if (cp->cp_index > end)
2533                         end = cp->cp_index;
2534                 if (cp->cp_index < start)
2535                         start = cp->cp_index;
2536                 ++page_count;
2537                 mppr <<= (page_count > mppr);
2538         }
2539
2540         ext = osc_extent_alloc(obj);
2541         if (ext == NULL) {
2542                 cfs_list_for_each_entry(oap, list, oap_pending_item) {
2543                         cfs_list_del_init(&oap->oap_pending_item);
2544                         osc_ap_completion(env, cli, oap, 0, -ENOMEM);
2545                 }
2546                 RETURN(-ENOMEM);
2547         }
2548
2549         ext->oe_rw = !!(cmd & OBD_BRW_READ);
2550         ext->oe_urgent = 1;
2551         ext->oe_start = start;
2552         ext->oe_end = ext->oe_max_end = end;
2553         ext->oe_obj = obj;
2554         ext->oe_srvlock = !!(brw_flags & OBD_BRW_SRVLOCK);
2555         ext->oe_nr_pages = page_count;
2556         ext->oe_mppr = mppr;
2557         cfs_list_splice_init(list, &ext->oe_pages);
2558
2559         osc_object_lock(obj);
2560         /* Reuse the initial refcount for RPC, don't drop it */
2561         osc_extent_state_set(ext, OES_LOCK_DONE);
2562         if (cmd & OBD_BRW_WRITE) {
2563                 cfs_list_add_tail(&ext->oe_link, &obj->oo_urgent_exts);
2564                 osc_update_pending(obj, OBD_BRW_WRITE, page_count);
2565         } else {
2566                 cfs_list_add_tail(&ext->oe_link, &obj->oo_reading_exts);
2567                 osc_update_pending(obj, OBD_BRW_READ, page_count);
2568         }
2569         osc_object_unlock(obj);
2570
2571         osc_io_unplug(env, cli, obj, PDL_POLICY_ROUND);
2572         RETURN(0);
2573 }
2574
2575 /**
2576  * Called by osc_io_setattr_start() to freeze and destroy covering extents.
2577  */
2578 int osc_cache_truncate_start(const struct lu_env *env, struct osc_io *oio,
2579                              struct osc_object *obj, __u64 size)
2580 {
2581         struct client_obd *cli = osc_cli(obj);
2582         struct osc_extent *ext;
2583         struct osc_extent *waiting = NULL;
2584         pgoff_t index;
2585         CFS_LIST_HEAD(list);
2586         int result = 0;
2587         bool partial;
2588         ENTRY;
2589
2590         /* pages with index greater or equal to index will be truncated. */
2591         index = cl_index(osc2cl(obj), size);
2592         partial = size > cl_offset(osc2cl(obj), index);
2593
2594 again:
2595         osc_object_lock(obj);
2596         ext = osc_extent_search(obj, index);
2597         if (ext == NULL)
2598                 ext = first_extent(obj);
2599         else if (ext->oe_end < index)
2600                 ext = next_extent(ext);
2601         while (ext != NULL) {
2602                 EASSERT(ext->oe_state != OES_TRUNC, ext);
2603
2604                 if (ext->oe_state > OES_CACHE || ext->oe_urgent) {
2605                         /* if ext is in urgent state, it means there must exist
2606                          * a page already having been flushed by write_page().
2607                          * We have to wait for this extent because we can't
2608                          * truncate that page. */
2609                         LASSERT(!ext->oe_hp);
2610                         OSC_EXTENT_DUMP(D_CACHE, ext,
2611                                         "waiting for busy extent\n");
2612                         waiting = osc_extent_get(ext);
2613                         break;
2614                 }
2615
2616                 osc_extent_get(ext);
2617                 if (ext->oe_state == OES_ACTIVE) {
2618                         /* though we grab inode mutex for write path, but we
2619                          * release it before releasing extent(in osc_io_end()),
2620                          * so there is a race window that an extent is still
2621                          * in OES_ACTIVE when truncate starts. */
2622                         LASSERT(!ext->oe_trunc_pending);
2623                         ext->oe_trunc_pending = 1;
2624                 } else {
2625                         EASSERT(ext->oe_state == OES_CACHE, ext);
2626                         osc_extent_state_set(ext, OES_TRUNC);
2627                         osc_update_pending(obj, OBD_BRW_WRITE,
2628                                            -ext->oe_nr_pages);
2629                 }
2630                 EASSERT(cfs_list_empty(&ext->oe_link), ext);
2631                 cfs_list_add_tail(&ext->oe_link, &list);
2632
2633                 ext = next_extent(ext);
2634         }
2635         osc_object_unlock(obj);
2636
2637         osc_list_maint(cli, obj);
2638
2639         while (!cfs_list_empty(&list)) {
2640                 int rc;
2641
2642                 ext = cfs_list_entry(list.next, struct osc_extent, oe_link);
2643                 cfs_list_del_init(&ext->oe_link);
2644
2645                 /* extent may be in OES_ACTIVE state because inode mutex
2646                  * is released before osc_io_end() in file write case */
2647                 if (ext->oe_state != OES_TRUNC)
2648                         osc_extent_wait(env, ext, OES_TRUNC);
2649
2650                 rc = osc_extent_truncate(ext, index, partial);
2651                 if (rc < 0) {
2652                         if (result == 0)
2653                                 result = rc;
2654
2655                         OSC_EXTENT_DUMP(D_ERROR, ext,
2656                                         "truncate error %d\n", rc);
2657                 } else if (ext->oe_nr_pages == 0) {
2658                         osc_extent_remove(ext);
2659                 } else {
2660                         /* this must be an overlapped extent which means only
2661                          * part of pages in this extent have been truncated.
2662                          */
2663                         EASSERTF(ext->oe_start <= index, ext,
2664                                  "trunc index = %lu/%d.\n", index, partial);
2665                         /* fix index to skip this partially truncated extent */
2666                         index = ext->oe_end + 1;
2667                         partial = false;
2668
2669                         /* we need to hold this extent in OES_TRUNC state so
2670                          * that no writeback will happen. This is to avoid
2671                          * BUG 17397. */
2672                         LASSERT(oio->oi_trunc == NULL);
2673                         oio->oi_trunc = osc_extent_get(ext);
2674                         OSC_EXTENT_DUMP(D_CACHE, ext,
2675                                         "trunc at "LPU64"\n", size);
2676                 }
2677                 osc_extent_put(env, ext);
2678         }
2679         if (waiting != NULL) {
2680                 if (result == 0)
2681                         result = osc_extent_wait(env, waiting, OES_INV);
2682
2683                 osc_extent_put(env, waiting);
2684                 waiting = NULL;
2685                 if (result == 0)
2686                         goto again;
2687         }
2688         RETURN(result);
2689 }
2690
2691 /**
2692  * Called after osc_io_setattr_end to add oio->oi_trunc back to cache.
2693  */
2694 void osc_cache_truncate_end(const struct lu_env *env, struct osc_io *oio,
2695                             struct osc_object *obj)
2696 {
2697         struct osc_extent *ext = oio->oi_trunc;
2698
2699         oio->oi_trunc = NULL;
2700         if (ext != NULL) {
2701                 EASSERT(ext->oe_nr_pages > 0, ext);
2702                 EASSERT(ext->oe_state == OES_TRUNC, ext);
2703                 EASSERT(!ext->oe_urgent, ext);
2704
2705                 OSC_EXTENT_DUMP(D_CACHE, ext, "trunc -> cache.\n");
2706                 osc_object_lock(obj);
2707                 osc_extent_state_set(ext, OES_CACHE);
2708                 if (ext->oe_fsync_wait && !ext->oe_urgent) {
2709                         ext->oe_urgent = 1;
2710                         cfs_list_move_tail(&ext->oe_link, &obj->oo_urgent_exts);
2711                 }
2712                 osc_update_pending(obj, OBD_BRW_WRITE, ext->oe_nr_pages);
2713                 osc_object_unlock(obj);
2714                 osc_extent_put(env, ext);
2715
2716                 osc_list_maint(osc_cli(obj), obj);
2717         }
2718 }
2719
2720 /**
2721  * Wait for extents in a specific range to be written out.
2722  * The caller must have called osc_cache_writeback_range() to issue IO
2723  * otherwise it will take a long time for this function to finish.
2724  *
2725  * Caller must hold inode_mutex , or cancel exclusive dlm lock so that
2726  * nobody else can dirty this range of file while we're waiting for
2727  * extents to be written.
2728  */
2729 int osc_cache_wait_range(const struct lu_env *env, struct osc_object *obj,
2730                          pgoff_t start, pgoff_t end)
2731 {
2732         struct osc_extent *ext;
2733         pgoff_t index = start;
2734         int     result = 0;
2735         ENTRY;
2736
2737 again:
2738         osc_object_lock(obj);
2739         ext = osc_extent_search(obj, index);
2740         if (ext == NULL)
2741                 ext = first_extent(obj);
2742         else if (ext->oe_end < index)
2743                 ext = next_extent(ext);
2744         while (ext != NULL) {
2745                 int rc;
2746
2747                 if (ext->oe_start > end)
2748                         break;
2749
2750                 if (!ext->oe_fsync_wait) {
2751                         ext = next_extent(ext);
2752                         continue;
2753                 }
2754
2755                 EASSERT(ergo(ext->oe_state == OES_CACHE,
2756                              ext->oe_hp || ext->oe_urgent), ext);
2757                 EASSERT(ergo(ext->oe_state == OES_ACTIVE,
2758                              !ext->oe_hp && ext->oe_urgent), ext);
2759
2760                 index = ext->oe_end + 1;
2761                 osc_extent_get(ext);
2762                 osc_object_unlock(obj);
2763
2764                 rc = osc_extent_wait(env, ext, OES_INV);
2765                 if (result == 0)
2766                         result = rc;
2767                 osc_extent_put(env, ext);
2768                 goto again;
2769         }
2770         osc_object_unlock(obj);
2771
2772         OSC_IO_DEBUG(obj, "sync file range.\n");
2773         RETURN(result);
2774 }
2775
2776 /**
2777  * Called to write out a range of osc object.
2778  *
2779  * @hp     : should be set this is caused by lock cancel;
2780  * @discard: is set if dirty pages should be dropped - file will be deleted or
2781  *         truncated, this implies there is no partially discarding extents.
2782  *
2783  * Return how many pages will be issued, or error code if error occurred.
2784  */
2785 int osc_cache_writeback_range(const struct lu_env *env, struct osc_object *obj,
2786                               pgoff_t start, pgoff_t end, int hp, int discard)
2787 {
2788         struct osc_extent *ext;
2789         CFS_LIST_HEAD(discard_list);
2790         int unplug = 0;
2791         int result = 0;
2792         ENTRY;
2793
2794         osc_object_lock(obj);
2795         ext = osc_extent_search(obj, start);
2796         if (ext == NULL)
2797                 ext = first_extent(obj);
2798         else if (ext->oe_end < start)
2799                 ext = next_extent(ext);
2800         while (ext != NULL) {
2801                 if (ext->oe_start > end)
2802                         break;
2803
2804                 ext->oe_fsync_wait = 1;
2805                 switch (ext->oe_state) {
2806                 case OES_CACHE:
2807                         result += ext->oe_nr_pages;
2808                         if (!discard) {
2809                                 cfs_list_t *list = NULL;
2810                                 if (hp) {
2811                                         EASSERT(!ext->oe_hp, ext);
2812                                         ext->oe_hp = 1;
2813                                         list = &obj->oo_hp_exts;
2814                                 } else if (!ext->oe_urgent) {
2815                                         ext->oe_urgent = 1;
2816                                         list = &obj->oo_urgent_exts;
2817                                 }
2818                                 if (list != NULL) {
2819                                         cfs_list_move_tail(&ext->oe_link, list);
2820                                         unplug = 1;
2821                                 }
2822                         } else {
2823                                 /* the only discarder is lock cancelling, so
2824                                  * [start, end] must contain this extent */
2825                                 EASSERT(ext->oe_start >= start &&
2826                                         ext->oe_max_end <= end, ext);
2827                                 osc_extent_state_set(ext, OES_LOCKING);
2828                                 ext->oe_owner = cfs_current();
2829                                 cfs_list_move_tail(&ext->oe_link,
2830                                                    &discard_list);
2831                                 osc_update_pending(obj, OBD_BRW_WRITE,
2832                                                    -ext->oe_nr_pages);
2833                         }
2834                         break;
2835                 case OES_ACTIVE:
2836                         /* It's pretty bad to wait for ACTIVE extents, because
2837                          * we don't know how long we will wait for it to be
2838                          * flushed since it may be blocked at awaiting more
2839                          * grants. We do this for the correctness of fsync. */
2840                         LASSERT(hp == 0 && discard == 0);
2841                         ext->oe_urgent = 1;
2842                         break;
2843                 case OES_TRUNC:
2844                         /* this extent is being truncated, can't do anything
2845                          * for it now. it will be set to urgent after truncate
2846                          * is finished in osc_cache_truncate_end(). */
2847                 default:
2848                         break;
2849                 }
2850                 ext = next_extent(ext);
2851         }
2852         osc_object_unlock(obj);
2853
2854         LASSERT(ergo(!discard, cfs_list_empty(&discard_list)));
2855         if (!cfs_list_empty(&discard_list)) {
2856                 struct osc_extent *tmp;
2857                 int rc;
2858
2859                 osc_list_maint(osc_cli(obj), obj);
2860                 cfs_list_for_each_entry_safe(ext, tmp, &discard_list, oe_link) {
2861                         cfs_list_del_init(&ext->oe_link);
2862                         EASSERT(ext->oe_state == OES_LOCKING, ext);
2863
2864                         /* Discard caching pages. We don't actually write this
2865                          * extent out but we complete it as if we did. */
2866                         rc = osc_extent_make_ready(env, ext);
2867                         if (unlikely(rc < 0)) {
2868                                 OSC_EXTENT_DUMP(D_ERROR, ext,
2869                                                 "make_ready returned %d\n", rc);
2870                                 if (result >= 0)
2871                                         result = rc;
2872                         }
2873
2874                         /* finish the extent as if the pages were sent */
2875                         osc_extent_finish(env, ext, 0, 0);
2876                 }
2877         }
2878
2879         if (unplug)
2880                 osc_io_unplug(env, osc_cli(obj), obj, PDL_POLICY_ROUND);
2881
2882         if (hp || discard) {
2883                 int rc;
2884                 rc = osc_cache_wait_range(env, obj, start, end);
2885                 if (result >= 0 && rc < 0)
2886                         result = rc;
2887         }
2888
2889         OSC_IO_DEBUG(obj, "cache page out.\n");
2890         RETURN(result);
2891 }
2892
2893 /** @} osc */