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