Whamcloud - gitweb
LU-2139 osc: Track and limit "unstable" pages
[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                 cfs_atomic_read(&__ext->oe_refc),                             \
116                 cfs_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 (cfs_atomic_read(&ext->oe_refc) <= 0)
188                 GOTO(out, rc = 20);
189
190         if (cfs_atomic_read(&ext->oe_refc) < cfs_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 (cfs_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 (cfs_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 = oap2cl_page(oap)->cp_index;
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         cfs_atomic_set(&ext->oe_refc, 1);
319         cfs_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(cfs_atomic_read(&ext->oe_refc) >= 0);
337         cfs_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(cfs_atomic_read(&ext->oe_refc) > 0);
344         if (cfs_atomic_dec_and_test(&ext->oe_refc)) {
345                 LASSERT(cfs_list_empty(&ext->oe_link));
346                 LASSERT(cfs_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(cfs_atomic_read(&ext->oe_refc) > 1);
366         LASSERT(osc_object_is_locked(ext->oe_obj));
367         cfs_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         cfs_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(cfs_atomic_read(&ext->oe_users) > 0);
546         LASSERT(sanity_check(ext) == 0);
547         LASSERT(ext->oe_grants > 0);
548
549         if (cfs_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         cfs_list_for_each_entry_safe(oap, tmp, &ext->oe_pages,
815                                      oap_pending_item) {
816                 cfs_list_del_init(&oap->oap_rpc_item);
817                 cfs_list_del_init(&oap->oap_pending_item);
818                 if (last_off <= oap->oap_obj_off) {
819                         last_off = oap->oap_obj_off;
820                         last_count = oap->oap_count;
821                 }
822
823                 --ext->oe_nr_pages;
824                 osc_ap_completion(env, cli, oap, sent, rc);
825         }
826         EASSERT(ext->oe_nr_pages == 0, ext);
827
828         if (!sent) {
829                 lost_grant = ext->oe_grants;
830         } else if (blocksize < PAGE_CACHE_SIZE &&
831                    last_count != PAGE_CACHE_SIZE) {
832                 /* For short writes we shouldn't count parts of pages that
833                  * span a whole chunk on the OST side, or our accounting goes
834                  * wrong.  Should match the code in filter_grant_check. */
835                 int offset = oap->oap_page_off & ~CFS_PAGE_MASK;
836                 int count = oap->oap_count + (offset & (blocksize - 1));
837                 int end = (offset + oap->oap_count) & (blocksize - 1);
838                 if (end)
839                         count += blocksize - end;
840
841                 lost_grant = PAGE_CACHE_SIZE - count;
842         }
843         if (ext->oe_grants > 0)
844                 osc_free_grant(cli, nr_pages, lost_grant);
845
846         osc_extent_remove(ext);
847         /* put the refcount for RPC */
848         osc_extent_put(env, ext);
849         RETURN(0);
850 }
851
852 static int extent_wait_cb(struct osc_extent *ext, int state)
853 {
854         int ret;
855
856         osc_object_lock(ext->oe_obj);
857         ret = ext->oe_state == state;
858         osc_object_unlock(ext->oe_obj);
859
860         return ret;
861 }
862
863 /**
864  * Wait for the extent's state to become @state.
865  */
866 static int osc_extent_wait(const struct lu_env *env, struct osc_extent *ext,
867                            int state)
868 {
869         struct osc_object *obj = ext->oe_obj;
870         struct l_wait_info lwi = LWI_TIMEOUT_INTR(cfs_time_seconds(600), NULL,
871                                                   LWI_ON_SIGNAL_NOOP, NULL);
872         int rc = 0;
873         ENTRY;
874
875         osc_object_lock(obj);
876         LASSERT(sanity_check_nolock(ext) == 0);
877         /* `Kick' this extent only if the caller is waiting for it to be
878          * written out. */
879         if (state == OES_INV && !ext->oe_urgent && !ext->oe_hp) {
880                 if (ext->oe_state == OES_ACTIVE) {
881                         ext->oe_urgent = 1;
882                 } else if (ext->oe_state == OES_CACHE) {
883                         ext->oe_urgent = 1;
884                         osc_extent_hold(ext);
885                         rc = 1;
886                 }
887         }
888         osc_object_unlock(obj);
889         if (rc == 1)
890                 osc_extent_release(env, ext);
891
892         /* wait for the extent until its state becomes @state */
893         rc = l_wait_event(ext->oe_waitq, extent_wait_cb(ext, state), &lwi);
894         if (rc == -ETIMEDOUT) {
895                 OSC_EXTENT_DUMP(D_ERROR, ext,
896                         "%s: wait ext to %d timedout, recovery in progress?\n",
897                         osc_export(obj)->exp_obd->obd_name, state);
898
899                 lwi = LWI_INTR(NULL, NULL);
900                 rc = l_wait_event(ext->oe_waitq, extent_wait_cb(ext, state),
901                                   &lwi);
902         }
903         if (rc == 0 && ext->oe_rc < 0)
904                 rc = ext->oe_rc;
905         RETURN(rc);
906 }
907
908 /**
909  * Discard pages with index greater than @size. If @ext is overlapped with
910  * @size, then partial truncate happens.
911  */
912 static int osc_extent_truncate(struct osc_extent *ext, pgoff_t trunc_index,
913                                 bool partial)
914 {
915         struct cl_env_nest     nest;
916         struct lu_env         *env;
917         struct cl_io          *io;
918         struct osc_object     *obj = ext->oe_obj;
919         struct client_obd     *cli = osc_cli(obj);
920         struct osc_async_page *oap;
921         struct osc_async_page *tmp;
922         int                    pages_in_chunk = 0;
923         int                    ppc_bits    = cli->cl_chunkbits -
924                                              PAGE_CACHE_SHIFT;
925         __u64                  trunc_chunk = trunc_index >> ppc_bits;
926         int                    grants   = 0;
927         int                    nr_pages = 0;
928         int                    rc       = 0;
929         ENTRY;
930
931         LASSERT(sanity_check(ext) == 0);
932         LASSERT(ext->oe_state == OES_TRUNC);
933         LASSERT(!ext->oe_urgent);
934
935         /* Request new lu_env.
936          * We can't use that env from osc_cache_truncate_start() because
937          * it's from lov_io_sub and not fully initialized. */
938         env = cl_env_nested_get(&nest);
939         io  = &osc_env_info(env)->oti_io;
940         io->ci_obj = cl_object_top(osc2cl(obj));
941         rc = cl_io_init(env, io, CIT_MISC, io->ci_obj);
942         if (rc < 0)
943                 GOTO(out, rc);
944
945         /* discard all pages with index greater then trunc_index */
946         cfs_list_for_each_entry_safe(oap, tmp, &ext->oe_pages,
947                                      oap_pending_item) {
948                 struct cl_page  *sub  = oap2cl_page(oap);
949                 struct cl_page  *page = cl_page_top(sub);
950
951                 LASSERT(cfs_list_empty(&oap->oap_rpc_item));
952
953                 /* only discard the pages with their index greater than
954                  * trunc_index, and ... */
955                 if (sub->cp_index < trunc_index ||
956                     (sub->cp_index == trunc_index && partial)) {
957                         /* accounting how many pages remaining in the chunk
958                          * so that we can calculate grants correctly. */
959                         if (sub->cp_index >> ppc_bits == trunc_chunk)
960                                 ++pages_in_chunk;
961                         continue;
962                 }
963
964                 cfs_list_del_init(&oap->oap_pending_item);
965
966                 cl_page_get(page);
967                 lu_ref_add(&page->cp_reference, "truncate", current);
968
969                 if (cl_page_own(env, io, page) == 0) {
970                         cl_page_unmap(env, io, page);
971                         cl_page_discard(env, io, page);
972                         cl_page_disown(env, io, page);
973                 } else {
974                         LASSERT(page->cp_state == CPS_FREEING);
975                         LASSERT(0);
976                 }
977
978                 lu_ref_del(&page->cp_reference, "truncate", current);
979                 cl_page_put(env, page);
980
981                 --ext->oe_nr_pages;
982                 ++nr_pages;
983         }
984         EASSERTF(ergo(ext->oe_start >= trunc_index + !!partial,
985                       ext->oe_nr_pages == 0),
986                 ext, "trunc_index %lu, partial %d\n", trunc_index, partial);
987
988         osc_object_lock(obj);
989         if (ext->oe_nr_pages == 0) {
990                 LASSERT(pages_in_chunk == 0);
991                 grants = ext->oe_grants;
992                 ext->oe_grants = 0;
993         } else { /* calculate how many grants we can free */
994                 int     chunks = (ext->oe_end >> ppc_bits) - trunc_chunk;
995                 pgoff_t last_index;
996
997
998                 /* if there is no pages in this chunk, we can also free grants
999                  * for the last chunk */
1000                 if (pages_in_chunk == 0) {
1001                         /* if this is the 1st chunk and no pages in this chunk,
1002                          * ext->oe_nr_pages must be zero, so we should be in
1003                          * the other if-clause. */
1004                         LASSERT(trunc_chunk > 0);
1005                         --trunc_chunk;
1006                         ++chunks;
1007                 }
1008
1009                 /* this is what we can free from this extent */
1010                 grants          = chunks << cli->cl_chunkbits;
1011                 ext->oe_grants -= grants;
1012                 last_index      = ((trunc_chunk + 1) << ppc_bits) - 1;
1013                 ext->oe_end     = min(last_index, ext->oe_max_end);
1014                 LASSERT(ext->oe_end >= ext->oe_start);
1015                 LASSERT(ext->oe_grants > 0);
1016         }
1017         osc_object_unlock(obj);
1018
1019         if (grants > 0 || nr_pages > 0)
1020                 osc_free_grant(cli, nr_pages, grants);
1021
1022 out:
1023         cl_io_fini(env, io);
1024         cl_env_nested_put(&nest, env);
1025         RETURN(rc);
1026 }
1027
1028 /**
1029  * This function is used to make the extent prepared for transfer.
1030  * A race with flusing page - ll_writepage() has to be handled cautiously.
1031  */
1032 static int osc_extent_make_ready(const struct lu_env *env,
1033                                  struct osc_extent *ext)
1034 {
1035         struct osc_async_page *oap;
1036         struct osc_async_page *last = NULL;
1037         struct osc_object *obj = ext->oe_obj;
1038         int page_count = 0;
1039         int rc;
1040         ENTRY;
1041
1042         /* we're going to grab page lock, so object lock must not be taken. */
1043         LASSERT(sanity_check(ext) == 0);
1044         /* in locking state, any process should not touch this extent. */
1045         EASSERT(ext->oe_state == OES_LOCKING, ext);
1046         EASSERT(ext->oe_owner != NULL, ext);
1047
1048         OSC_EXTENT_DUMP(D_CACHE, ext, "make ready\n");
1049
1050         cfs_list_for_each_entry(oap, &ext->oe_pages, oap_pending_item) {
1051                 ++page_count;
1052                 if (last == NULL || last->oap_obj_off < oap->oap_obj_off)
1053                         last = oap;
1054
1055                 /* checking ASYNC_READY is race safe */
1056                 if ((oap->oap_async_flags & ASYNC_READY) != 0)
1057                         continue;
1058
1059                 rc = osc_make_ready(env, oap, OBD_BRW_WRITE);
1060                 switch (rc) {
1061                 case 0:
1062                         spin_lock(&oap->oap_lock);
1063                         oap->oap_async_flags |= ASYNC_READY;
1064                         spin_unlock(&oap->oap_lock);
1065                         break;
1066                 case -EALREADY:
1067                         LASSERT((oap->oap_async_flags & ASYNC_READY) != 0);
1068                         break;
1069                 default:
1070                         LASSERTF(0, "unknown return code: %d\n", rc);
1071                 }
1072         }
1073
1074         LASSERT(page_count == ext->oe_nr_pages);
1075         LASSERT(last != NULL);
1076         /* the last page is the only one we need to refresh its count by
1077          * the size of file. */
1078         if (!(last->oap_async_flags & ASYNC_COUNT_STABLE)) {
1079                 last->oap_count = osc_refresh_count(env, last, OBD_BRW_WRITE);
1080                 LASSERT(last->oap_count > 0);
1081                 LASSERT(last->oap_page_off + last->oap_count <= PAGE_CACHE_SIZE);
1082                 spin_lock(&last->oap_lock);
1083                 last->oap_async_flags |= ASYNC_COUNT_STABLE;
1084                 spin_unlock(&last->oap_lock);
1085         }
1086
1087         /* for the rest of pages, we don't need to call osf_refresh_count()
1088          * because it's known they are not the last page */
1089         cfs_list_for_each_entry(oap, &ext->oe_pages, oap_pending_item) {
1090                 if (!(oap->oap_async_flags & ASYNC_COUNT_STABLE)) {
1091                         oap->oap_count = PAGE_CACHE_SIZE - oap->oap_page_off;
1092                         spin_lock(&oap->oap_lock);
1093                         oap->oap_async_flags |= ASYNC_COUNT_STABLE;
1094                         spin_unlock(&oap->oap_lock);
1095                 }
1096         }
1097
1098         osc_object_lock(obj);
1099         osc_extent_state_set(ext, OES_RPC);
1100         osc_object_unlock(obj);
1101         /* get a refcount for RPC. */
1102         osc_extent_get(ext);
1103
1104         RETURN(0);
1105 }
1106
1107 /**
1108  * Quick and simple version of osc_extent_find(). This function is frequently
1109  * called to expand the extent for the same IO. To expand the extent, the
1110  * page index must be in the same or next chunk of ext->oe_end.
1111  */
1112 static int osc_extent_expand(struct osc_extent *ext, pgoff_t index, int *grants)
1113 {
1114         struct osc_object *obj = ext->oe_obj;
1115         struct client_obd *cli = osc_cli(obj);
1116         struct osc_extent *next;
1117         int ppc_bits = cli->cl_chunkbits - PAGE_CACHE_SHIFT;
1118         pgoff_t chunk = index >> ppc_bits;
1119         pgoff_t end_chunk;
1120         pgoff_t end_index;
1121         int chunksize = 1 << cli->cl_chunkbits;
1122         int rc = 0;
1123         ENTRY;
1124
1125         LASSERT(ext->oe_max_end >= index && ext->oe_start <= index);
1126         osc_object_lock(obj);
1127         LASSERT(sanity_check_nolock(ext) == 0);
1128         end_chunk = ext->oe_end >> ppc_bits;
1129         if (chunk > end_chunk + 1)
1130                 GOTO(out, rc = -ERANGE);
1131
1132         if (end_chunk >= chunk)
1133                 GOTO(out, rc = 0);
1134
1135         LASSERT(end_chunk + 1 == chunk);
1136         /* try to expand this extent to cover @index */
1137         end_index = min(ext->oe_max_end, ((chunk + 1) << ppc_bits) - 1);
1138
1139         next = next_extent(ext);
1140         if (next != NULL && next->oe_start <= end_index)
1141                 /* complex mode - overlapped with the next extent,
1142                  * this case will be handled by osc_extent_find() */
1143                 GOTO(out, rc = -EAGAIN);
1144
1145         ext->oe_end = end_index;
1146         ext->oe_grants += chunksize;
1147         *grants -= chunksize;
1148         LASSERT(*grants >= 0);
1149         EASSERTF(osc_extent_is_overlapped(obj, ext) == 0, ext,
1150                  "overlapped after expanding for %lu.\n", index);
1151         EXIT;
1152
1153 out:
1154         osc_object_unlock(obj);
1155         RETURN(rc);
1156 }
1157
1158 static void osc_extent_tree_dump0(int level, struct osc_object *obj,
1159                                   const char *func, int line)
1160 {
1161         struct osc_extent *ext;
1162         int cnt;
1163
1164         CDEBUG(level, "Dump object %p extents at %s:%d, mppr: %u.\n",
1165                obj, func, line, osc_cli(obj)->cl_max_pages_per_rpc);
1166
1167         /* osc_object_lock(obj); */
1168         cnt = 1;
1169         for (ext = first_extent(obj); ext != NULL; ext = next_extent(ext))
1170                 OSC_EXTENT_DUMP(level, ext, "in tree %d.\n", cnt++);
1171
1172         cnt = 1;
1173         cfs_list_for_each_entry(ext, &obj->oo_hp_exts, oe_link)
1174                 OSC_EXTENT_DUMP(level, ext, "hp %d.\n", cnt++);
1175
1176         cnt = 1;
1177         cfs_list_for_each_entry(ext, &obj->oo_urgent_exts, oe_link)
1178                 OSC_EXTENT_DUMP(level, ext, "urgent %d.\n", cnt++);
1179
1180         cnt = 1;
1181         cfs_list_for_each_entry(ext, &obj->oo_reading_exts, oe_link)
1182                 OSC_EXTENT_DUMP(level, ext, "reading %d.\n", cnt++);
1183         /* osc_object_unlock(obj); */
1184 }
1185
1186 /* ------------------ osc extent end ------------------ */
1187
1188 static inline int osc_is_ready(struct osc_object *osc)
1189 {
1190         return !cfs_list_empty(&osc->oo_ready_item) ||
1191                !cfs_list_empty(&osc->oo_hp_ready_item);
1192 }
1193
1194 #define OSC_IO_DEBUG(OSC, STR, args...)                                        \
1195         CDEBUG(D_CACHE, "obj %p ready %d|%c|%c wr %d|%c|%c rd %d|%c " STR,     \
1196                (OSC), osc_is_ready(OSC),                                       \
1197                list_empty_marker(&(OSC)->oo_hp_ready_item),                    \
1198                list_empty_marker(&(OSC)->oo_ready_item),                       \
1199                cfs_atomic_read(&(OSC)->oo_nr_writes),                          \
1200                list_empty_marker(&(OSC)->oo_hp_exts),                          \
1201                list_empty_marker(&(OSC)->oo_urgent_exts),                      \
1202                cfs_atomic_read(&(OSC)->oo_nr_reads),                           \
1203                list_empty_marker(&(OSC)->oo_reading_exts),                     \
1204                ##args)
1205
1206 static int osc_make_ready(const struct lu_env *env, struct osc_async_page *oap,
1207                           int cmd)
1208 {
1209         struct osc_page *opg  = oap2osc_page(oap);
1210         struct cl_page  *page = cl_page_top(oap2cl_page(oap));
1211         int result;
1212
1213         LASSERT(cmd == OBD_BRW_WRITE); /* no cached reads */
1214
1215         ENTRY;
1216         result = cl_page_make_ready(env, page, CRT_WRITE);
1217         if (result == 0)
1218                 opg->ops_submit_time = cfs_time_current();
1219         RETURN(result);
1220 }
1221
1222 static int osc_refresh_count(const struct lu_env *env,
1223                              struct osc_async_page *oap, int cmd)
1224 {
1225         struct osc_page  *opg = oap2osc_page(oap);
1226         struct cl_page   *page = oap2cl_page(oap);
1227         struct cl_object *obj;
1228         struct cl_attr   *attr = &osc_env_info(env)->oti_attr;
1229
1230         int result;
1231         loff_t kms;
1232
1233         /* readpage queues with _COUNT_STABLE, shouldn't get here. */
1234         LASSERT(!(cmd & OBD_BRW_READ));
1235         LASSERT(opg != NULL);
1236         obj = opg->ops_cl.cpl_obj;
1237
1238         cl_object_attr_lock(obj);
1239         result = cl_object_attr_get(env, obj, attr);
1240         cl_object_attr_unlock(obj);
1241         if (result < 0)
1242                 return result;
1243         kms = attr->cat_kms;
1244         if (cl_offset(obj, page->cp_index) >= kms)
1245                 /* catch race with truncate */
1246                 return 0;
1247         else if (cl_offset(obj, page->cp_index + 1) > kms)
1248                 /* catch sub-page write at end of file */
1249                 return kms % PAGE_CACHE_SIZE;
1250         else
1251                 return PAGE_CACHE_SIZE;
1252 }
1253
1254 static int osc_completion(const struct lu_env *env, struct osc_async_page *oap,
1255                           int cmd, int rc)
1256 {
1257         struct osc_page   *opg  = oap2osc_page(oap);
1258         struct cl_page    *page = cl_page_top(oap2cl_page(oap));
1259         struct osc_object *obj  = cl2osc(opg->ops_cl.cpl_obj);
1260         enum cl_req_type   crt;
1261         int srvlock;
1262
1263         ENTRY;
1264
1265         cmd &= ~OBD_BRW_NOQUOTA;
1266         LASSERTF(equi(page->cp_state == CPS_PAGEIN,  cmd == OBD_BRW_READ),
1267                  "cp_state:%u, cmd:%d\n", page->cp_state, cmd);
1268         LASSERTF(equi(page->cp_state == CPS_PAGEOUT, cmd == OBD_BRW_WRITE),
1269                 "cp_state:%u, cmd:%d\n", page->cp_state, cmd);
1270         LASSERT(opg->ops_transfer_pinned);
1271
1272         /*
1273          * page->cp_req can be NULL if io submission failed before
1274          * cl_req was allocated.
1275          */
1276         if (page->cp_req != NULL)
1277                 cl_req_page_done(env, page);
1278         LASSERT(page->cp_req == NULL);
1279
1280         crt = cmd == OBD_BRW_READ ? CRT_READ : CRT_WRITE;
1281         /* Clear opg->ops_transfer_pinned before VM lock is released. */
1282         opg->ops_transfer_pinned = 0;
1283
1284         spin_lock(&obj->oo_seatbelt);
1285         LASSERT(opg->ops_submitter != NULL);
1286         LASSERT(!cfs_list_empty(&opg->ops_inflight));
1287         cfs_list_del_init(&opg->ops_inflight);
1288         opg->ops_submitter = NULL;
1289         spin_unlock(&obj->oo_seatbelt);
1290
1291         opg->ops_submit_time = 0;
1292         srvlock = oap->oap_brw_flags & OBD_BRW_SRVLOCK;
1293
1294         /* statistic */
1295         if (rc == 0 && srvlock) {
1296                 struct lu_device *ld    = opg->ops_cl.cpl_obj->co_lu.lo_dev;
1297                 struct osc_stats *stats = &lu2osc_dev(ld)->od_stats;
1298                 int bytes = oap->oap_count;
1299
1300                 if (crt == CRT_READ)
1301                         stats->os_lockless_reads += bytes;
1302                 else
1303                         stats->os_lockless_writes += bytes;
1304         }
1305
1306         /*
1307          * This has to be the last operation with the page, as locks are
1308          * released in cl_page_completion() and nothing except for the
1309          * reference counter protects page from concurrent reclaim.
1310          */
1311         lu_ref_del(&page->cp_reference, "transfer", page);
1312
1313         cl_page_completion(env, page, crt, rc);
1314
1315         RETURN(0);
1316 }
1317
1318 #define OSC_DUMP_GRANT(lvl, cli, fmt, args...) do {                           \
1319         struct client_obd *__tmp = (cli);                                     \
1320         CDEBUG(lvl, "%s: grant { dirty: %ld/%ld dirty_pages: %d/%d "          \
1321                "unstable_pages: %d/%d dropped: %ld avail: %ld, "              \
1322                "reserved: %ld, flight: %d } lru {in list: %d, "               \
1323                "left: %d, waiters: %d }" fmt,                                 \
1324                __tmp->cl_import->imp_obd->obd_name,                           \
1325                __tmp->cl_dirty, __tmp->cl_dirty_max,                          \
1326                cfs_atomic_read(&obd_dirty_pages), obd_max_dirty_pages,        \
1327                cfs_atomic_read(&obd_unstable_pages), obd_max_dirty_pages,     \
1328                __tmp->cl_lost_grant, __tmp->cl_avail_grant,                   \
1329                __tmp->cl_reserved_grant, __tmp->cl_w_in_flight,               \
1330                cfs_atomic_read(&__tmp->cl_lru_in_list),                       \
1331                cfs_atomic_read(&__tmp->cl_lru_busy),                          \
1332                cfs_atomic_read(&__tmp->cl_lru_shrinkers), ##args);            \
1333 } while (0)
1334
1335 /* caller must hold loi_list_lock */
1336 static void osc_consume_write_grant(struct client_obd *cli,
1337                                     struct brw_page *pga)
1338 {
1339         LASSERT(spin_is_locked(&cli->cl_loi_list_lock.lock));
1340         LASSERT(!(pga->flag & OBD_BRW_FROM_GRANT));
1341         cfs_atomic_inc(&obd_dirty_pages);
1342         cli->cl_dirty += PAGE_CACHE_SIZE;
1343         pga->flag |= OBD_BRW_FROM_GRANT;
1344         CDEBUG(D_CACHE, "using %lu grant credits for brw %p page %p\n",
1345                PAGE_CACHE_SIZE, pga, pga->pg);
1346         osc_update_next_shrink(cli);
1347 }
1348
1349 /* the companion to osc_consume_write_grant, called when a brw has completed.
1350  * must be called with the loi lock held. */
1351 static void osc_release_write_grant(struct client_obd *cli,
1352                                     struct brw_page *pga)
1353 {
1354         ENTRY;
1355
1356         LASSERT(spin_is_locked(&cli->cl_loi_list_lock.lock));
1357         if (!(pga->flag & OBD_BRW_FROM_GRANT)) {
1358                 EXIT;
1359                 return;
1360         }
1361
1362         pga->flag &= ~OBD_BRW_FROM_GRANT;
1363         cfs_atomic_dec(&obd_dirty_pages);
1364         cli->cl_dirty -= PAGE_CACHE_SIZE;
1365         if (pga->flag & OBD_BRW_NOCACHE) {
1366                 pga->flag &= ~OBD_BRW_NOCACHE;
1367                 cfs_atomic_dec(&obd_dirty_transit_pages);
1368                 cli->cl_dirty_transit -= PAGE_CACHE_SIZE;
1369         }
1370         EXIT;
1371 }
1372
1373 /**
1374  * To avoid sleeping with object lock held, it's good for us allocate enough
1375  * grants before entering into critical section.
1376  *
1377  * client_obd_list_lock held by caller
1378  */
1379 static int osc_reserve_grant(struct client_obd *cli, unsigned int bytes)
1380 {
1381         int rc = -EDQUOT;
1382
1383         if (cli->cl_avail_grant >= bytes) {
1384                 cli->cl_avail_grant    -= bytes;
1385                 cli->cl_reserved_grant += bytes;
1386                 rc = 0;
1387         }
1388         return rc;
1389 }
1390
1391 static void __osc_unreserve_grant(struct client_obd *cli,
1392                                   unsigned int reserved, unsigned int unused)
1393 {
1394         /* it's quite normal for us to get more grant than reserved.
1395          * Thinking about a case that two extents merged by adding a new
1396          * chunk, we can save one extent tax. If extent tax is greater than
1397          * one chunk, we can save more grant by adding a new chunk */
1398         cli->cl_reserved_grant -= reserved;
1399         if (unused > reserved) {
1400                 cli->cl_avail_grant += reserved;
1401                 cli->cl_lost_grant  += unused - reserved;
1402         } else {
1403                 cli->cl_avail_grant += unused;
1404         }
1405 }
1406
1407 void osc_unreserve_grant(struct client_obd *cli,
1408                          unsigned int reserved, unsigned int unused)
1409 {
1410         client_obd_list_lock(&cli->cl_loi_list_lock);
1411         __osc_unreserve_grant(cli, reserved, unused);
1412         if (unused > 0)
1413                 osc_wake_cache_waiters(cli);
1414         client_obd_list_unlock(&cli->cl_loi_list_lock);
1415 }
1416
1417 /**
1418  * Free grant after IO is finished or canceled.
1419  *
1420  * @lost_grant is used to remember how many grants we have allocated but not
1421  * used, we should return these grants to OST. There're two cases where grants
1422  * can be lost:
1423  * 1. truncate;
1424  * 2. blocksize at OST is less than PAGE_CACHE_SIZE and a partial page was
1425  *    written. In this case OST may use less chunks to serve this partial
1426  *    write. OSTs don't actually know the page size on the client side. so
1427  *    clients have to calculate lost grant by the blocksize on the OST.
1428  *    See filter_grant_check() for details.
1429  */
1430 static void osc_free_grant(struct client_obd *cli, unsigned int nr_pages,
1431                            unsigned int lost_grant)
1432 {
1433         int grant = (1 << cli->cl_chunkbits) + cli->cl_extent_tax;
1434
1435         client_obd_list_lock(&cli->cl_loi_list_lock);
1436         cfs_atomic_sub(nr_pages, &obd_dirty_pages);
1437         cli->cl_dirty -= nr_pages << PAGE_CACHE_SHIFT;
1438         cli->cl_lost_grant += lost_grant;
1439         if (cli->cl_avail_grant < grant && cli->cl_lost_grant >= grant) {
1440                 /* borrow some grant from truncate to avoid the case that
1441                  * truncate uses up all avail grant */
1442                 cli->cl_lost_grant -= grant;
1443                 cli->cl_avail_grant += grant;
1444         }
1445         osc_wake_cache_waiters(cli);
1446         client_obd_list_unlock(&cli->cl_loi_list_lock);
1447         CDEBUG(D_CACHE, "lost %u grant: %lu avail: %lu dirty: %lu\n",
1448                lost_grant, cli->cl_lost_grant,
1449                cli->cl_avail_grant, cli->cl_dirty);
1450 }
1451
1452 /**
1453  * The companion to osc_enter_cache(), called when @oap is no longer part of
1454  * the dirty accounting due to error.
1455  */
1456 static void osc_exit_cache(struct client_obd *cli, struct osc_async_page *oap)
1457 {
1458         client_obd_list_lock(&cli->cl_loi_list_lock);
1459         osc_release_write_grant(cli, &oap->oap_brw_page);
1460         client_obd_list_unlock(&cli->cl_loi_list_lock);
1461 }
1462
1463 /**
1464  * Non-blocking version of osc_enter_cache() that consumes grant only when it
1465  * is available.
1466  */
1467 static int osc_enter_cache_try(struct client_obd *cli,
1468                                struct osc_async_page *oap,
1469                                int bytes, int transient)
1470 {
1471         int rc;
1472
1473         OSC_DUMP_GRANT(D_CACHE, cli, "need:%d.\n", bytes);
1474
1475         rc = osc_reserve_grant(cli, bytes);
1476         if (rc < 0)
1477                 return 0;
1478
1479         if (cli->cl_dirty + PAGE_CACHE_SIZE <= cli->cl_dirty_max &&
1480             cfs_atomic_read(&obd_unstable_pages) + 1 +
1481             cfs_atomic_read(&obd_dirty_pages) <= obd_max_dirty_pages) {
1482                 osc_consume_write_grant(cli, &oap->oap_brw_page);
1483                 if (transient) {
1484                         cli->cl_dirty_transit += PAGE_CACHE_SIZE;
1485                         cfs_atomic_inc(&obd_dirty_transit_pages);
1486                         oap->oap_brw_flags |= OBD_BRW_NOCACHE;
1487                 }
1488                 rc = 1;
1489         } else {
1490                 __osc_unreserve_grant(cli, bytes, bytes);
1491                 rc = 0;
1492         }
1493         return rc;
1494 }
1495
1496 static int ocw_granted(struct client_obd *cli, struct osc_cache_waiter *ocw)
1497 {
1498         int rc;
1499         client_obd_list_lock(&cli->cl_loi_list_lock);
1500         rc = cfs_list_empty(&ocw->ocw_entry);
1501         client_obd_list_unlock(&cli->cl_loi_list_lock);
1502         return rc;
1503 }
1504
1505 /**
1506  * The main entry to reserve dirty page accounting. Usually the grant reserved
1507  * in this function will be freed in bulk in osc_free_grant() unless it fails
1508  * to add osc cache, in that case, it will be freed in osc_exit_cache().
1509  *
1510  * The process will be put into sleep if it's already run out of grant.
1511  */
1512 static int osc_enter_cache(const struct lu_env *env, struct client_obd *cli,
1513                            struct osc_async_page *oap, int bytes)
1514 {
1515         struct osc_object *osc = oap->oap_obj;
1516         struct lov_oinfo  *loi = osc->oo_oinfo;
1517         struct osc_cache_waiter ocw;
1518         struct l_wait_info lwi = LWI_TIMEOUT_INTR(cfs_time_seconds(600), NULL,
1519                                                   LWI_ON_SIGNAL_NOOP, NULL);
1520         int rc = -EDQUOT;
1521         ENTRY;
1522
1523         OSC_DUMP_GRANT(D_CACHE, cli, "need:%d.\n", bytes);
1524
1525         client_obd_list_lock(&cli->cl_loi_list_lock);
1526
1527         /* force the caller to try sync io.  this can jump the list
1528          * of queued writes and create a discontiguous rpc stream */
1529         if (OBD_FAIL_CHECK(OBD_FAIL_OSC_NO_GRANT) ||
1530             cli->cl_dirty_max < PAGE_CACHE_SIZE     ||
1531             cli->cl_ar.ar_force_sync || loi->loi_ar.ar_force_sync)
1532                 GOTO(out, rc = -EDQUOT);
1533
1534         /* Hopefully normal case - cache space and write credits available */
1535         if (osc_enter_cache_try(cli, oap, bytes, 0))
1536                 GOTO(out, rc = 0);
1537
1538         /* We can get here for two reasons: too many dirty pages in cache, or
1539          * run out of grants. In both cases we should write dirty pages out.
1540          * Adding a cache waiter will trigger urgent write-out no matter what
1541          * RPC size will be.
1542          * The exiting condition is no avail grants and no dirty pages caching,
1543          * that really means there is no space on the OST. */
1544         init_waitqueue_head(&ocw.ocw_waitq);
1545         ocw.ocw_oap   = oap;
1546         ocw.ocw_grant = bytes;
1547         while (cli->cl_dirty > 0 || cli->cl_w_in_flight > 0) {
1548                 cfs_list_add_tail(&ocw.ocw_entry, &cli->cl_cache_waiters);
1549                 ocw.ocw_rc = 0;
1550                 client_obd_list_unlock(&cli->cl_loi_list_lock);
1551
1552                 osc_io_unplug_async(env, cli, NULL);
1553
1554                 CDEBUG(D_CACHE, "%s: sleeping for cache space @ %p for %p\n",
1555                        cli->cl_import->imp_obd->obd_name, &ocw, oap);
1556
1557                 rc = l_wait_event(ocw.ocw_waitq, ocw_granted(cli, &ocw), &lwi);
1558
1559                 client_obd_list_lock(&cli->cl_loi_list_lock);
1560
1561                 /* l_wait_event is interrupted by signal, or timed out */
1562                 if (rc < 0) {
1563                         switch (rc) {
1564                         case -ETIMEDOUT:
1565                                 OSC_DUMP_GRANT(D_ERROR, cli,
1566                                                 "try to reserve %d.\n", bytes);
1567                                 osc_extent_tree_dump(D_ERROR, osc);
1568                                 rc = -EDQUOT;
1569                                 break;
1570                         case -EINTR:
1571                                 /* Ensures restartability - LU-3581 */
1572                                 rc = -ERESTARTSYS;
1573                                 break;
1574                         default:
1575                                 CDEBUG(D_CACHE, "%s: event for cache space @"
1576                                        " %p never arrived due to %d\n",
1577                                        cli->cl_import->imp_obd->obd_name,
1578                                        &ocw, rc);
1579                                 break;
1580                         }
1581                         cfs_list_del_init(&ocw.ocw_entry);
1582                         GOTO(out, rc);
1583                 }
1584
1585                 LASSERT(cfs_list_empty(&ocw.ocw_entry));
1586                 rc = ocw.ocw_rc;
1587
1588                 if (rc != -EDQUOT)
1589                         GOTO(out, rc);
1590                 if (osc_enter_cache_try(cli, oap, bytes, 0))
1591                         GOTO(out, rc = 0);
1592         }
1593         EXIT;
1594 out:
1595         client_obd_list_unlock(&cli->cl_loi_list_lock);
1596         OSC_DUMP_GRANT(D_CACHE, cli, "returned %d.\n", rc);
1597         RETURN(rc);
1598 }
1599
1600 /* caller must hold loi_list_lock */
1601 void osc_wake_cache_waiters(struct client_obd *cli)
1602 {
1603         cfs_list_t *l, *tmp;
1604         struct osc_cache_waiter *ocw;
1605
1606         ENTRY;
1607         cfs_list_for_each_safe(l, tmp, &cli->cl_cache_waiters) {
1608                 ocw = cfs_list_entry(l, struct osc_cache_waiter, ocw_entry);
1609                 cfs_list_del_init(&ocw->ocw_entry);
1610
1611                 ocw->ocw_rc = -EDQUOT;
1612                 /* we can't dirty more */
1613                 if ((cli->cl_dirty + PAGE_CACHE_SIZE > cli->cl_dirty_max) ||
1614                     (cfs_atomic_read(&obd_unstable_pages) + 1 +
1615                      cfs_atomic_read(&obd_dirty_pages) > obd_max_dirty_pages)) {
1616                         CDEBUG(D_CACHE, "no dirty room: dirty: %ld "
1617                                "osc max %ld, sys max %d\n", cli->cl_dirty,
1618                                cli->cl_dirty_max, obd_max_dirty_pages);
1619                         goto wakeup;
1620                 }
1621
1622                 ocw->ocw_rc = 0;
1623                 if (!osc_enter_cache_try(cli, ocw->ocw_oap, ocw->ocw_grant, 0))
1624                         ocw->ocw_rc = -EDQUOT;
1625
1626 wakeup:
1627                 CDEBUG(D_CACHE, "wake up %p for oap %p, avail grant %ld, %d\n",
1628                        ocw, ocw->ocw_oap, cli->cl_avail_grant, ocw->ocw_rc);
1629
1630                 wake_up(&ocw->ocw_waitq);
1631         }
1632
1633         EXIT;
1634 }
1635
1636 static int osc_max_rpc_in_flight(struct client_obd *cli, struct osc_object *osc)
1637 {
1638         int hprpc = !!cfs_list_empty(&osc->oo_hp_exts);
1639         return rpcs_in_flight(cli) >= cli->cl_max_rpcs_in_flight + hprpc;
1640 }
1641
1642 /* This maintains the lists of pending pages to read/write for a given object
1643  * (lop).  This is used by osc_check_rpcs->osc_next_obj() and osc_list_maint()
1644  * to quickly find objects that are ready to send an RPC. */
1645 static int osc_makes_rpc(struct client_obd *cli, struct osc_object *osc,
1646                          int cmd)
1647 {
1648         int invalid_import = 0;
1649         ENTRY;
1650
1651         /* if we have an invalid import we want to drain the queued pages
1652          * by forcing them through rpcs that immediately fail and complete
1653          * the pages.  recovery relies on this to empty the queued pages
1654          * before canceling the locks and evicting down the llite pages */
1655         if ((cli->cl_import == NULL || cli->cl_import->imp_invalid))
1656                 invalid_import = 1;
1657
1658         if (cmd & OBD_BRW_WRITE) {
1659                 if (cfs_atomic_read(&osc->oo_nr_writes) == 0)
1660                         RETURN(0);
1661                 if (invalid_import) {
1662                         CDEBUG(D_CACHE, "invalid import forcing RPC\n");
1663                         RETURN(1);
1664                 }
1665                 if (!cfs_list_empty(&osc->oo_hp_exts)) {
1666                         CDEBUG(D_CACHE, "high prio request forcing RPC\n");
1667                         RETURN(1);
1668                 }
1669                 if (!cfs_list_empty(&osc->oo_urgent_exts)) {
1670                         CDEBUG(D_CACHE, "urgent request forcing RPC\n");
1671                         RETURN(1);
1672                 }
1673                 /* trigger a write rpc stream as long as there are dirtiers
1674                  * waiting for space.  as they're waiting, they're not going to
1675                  * create more pages to coalesce with what's waiting.. */
1676                 if (!cfs_list_empty(&cli->cl_cache_waiters)) {
1677                         CDEBUG(D_CACHE, "cache waiters forcing RPC\n");
1678                         RETURN(1);
1679                 }
1680                 if (cfs_atomic_read(&osc->oo_nr_writes) >=
1681                     cli->cl_max_pages_per_rpc)
1682                         RETURN(1);
1683         } else {
1684                 if (cfs_atomic_read(&osc->oo_nr_reads) == 0)
1685                         RETURN(0);
1686                 if (invalid_import) {
1687                         CDEBUG(D_CACHE, "invalid import forcing RPC\n");
1688                         RETURN(1);
1689                 }
1690                 /* all read are urgent. */
1691                 if (!cfs_list_empty(&osc->oo_reading_exts))
1692                         RETURN(1);
1693         }
1694
1695         RETURN(0);
1696 }
1697
1698 static void osc_update_pending(struct osc_object *obj, int cmd, int delta)
1699 {
1700         struct client_obd *cli = osc_cli(obj);
1701         if (cmd & OBD_BRW_WRITE) {
1702                 cfs_atomic_add(delta, &obj->oo_nr_writes);
1703                 cfs_atomic_add(delta, &cli->cl_pending_w_pages);
1704                 LASSERT(cfs_atomic_read(&obj->oo_nr_writes) >= 0);
1705         } else {
1706                 cfs_atomic_add(delta, &obj->oo_nr_reads);
1707                 cfs_atomic_add(delta, &cli->cl_pending_r_pages);
1708                 LASSERT(cfs_atomic_read(&obj->oo_nr_reads) >= 0);
1709         }
1710         OSC_IO_DEBUG(obj, "update pending cmd %d delta %d.\n", cmd, delta);
1711 }
1712
1713 static int osc_makes_hprpc(struct osc_object *obj)
1714 {
1715         return !cfs_list_empty(&obj->oo_hp_exts);
1716 }
1717
1718 static void on_list(cfs_list_t *item, cfs_list_t *list, int should_be_on)
1719 {
1720         if (cfs_list_empty(item) && should_be_on)
1721                 cfs_list_add_tail(item, list);
1722         else if (!cfs_list_empty(item) && !should_be_on)
1723                 cfs_list_del_init(item);
1724 }
1725
1726 /* maintain the osc's cli list membership invariants so that osc_send_oap_rpc
1727  * can find pages to build into rpcs quickly */
1728 static int __osc_list_maint(struct client_obd *cli, struct osc_object *osc)
1729 {
1730         if (osc_makes_hprpc(osc)) {
1731                 /* HP rpc */
1732                 on_list(&osc->oo_ready_item, &cli->cl_loi_ready_list, 0);
1733                 on_list(&osc->oo_hp_ready_item, &cli->cl_loi_hp_ready_list, 1);
1734         } else {
1735                 on_list(&osc->oo_hp_ready_item, &cli->cl_loi_hp_ready_list, 0);
1736                 on_list(&osc->oo_ready_item, &cli->cl_loi_ready_list,
1737                         osc_makes_rpc(cli, osc, OBD_BRW_WRITE) ||
1738                         osc_makes_rpc(cli, osc, OBD_BRW_READ));
1739         }
1740
1741         on_list(&osc->oo_write_item, &cli->cl_loi_write_list,
1742                 cfs_atomic_read(&osc->oo_nr_writes) > 0);
1743
1744         on_list(&osc->oo_read_item, &cli->cl_loi_read_list,
1745                 cfs_atomic_read(&osc->oo_nr_reads) > 0);
1746
1747         return osc_is_ready(osc);
1748 }
1749
1750 static int osc_list_maint(struct client_obd *cli, struct osc_object *osc)
1751 {
1752         int is_ready;
1753
1754         client_obd_list_lock(&cli->cl_loi_list_lock);
1755         is_ready = __osc_list_maint(cli, osc);
1756         client_obd_list_unlock(&cli->cl_loi_list_lock);
1757
1758         return is_ready;
1759 }
1760
1761 /* this is trying to propogate async writeback errors back up to the
1762  * application.  As an async write fails we record the error code for later if
1763  * the app does an fsync.  As long as errors persist we force future rpcs to be
1764  * sync so that the app can get a sync error and break the cycle of queueing
1765  * pages for which writeback will fail. */
1766 static void osc_process_ar(struct osc_async_rc *ar, __u64 xid,
1767                            int rc)
1768 {
1769         if (rc) {
1770                 if (!ar->ar_rc)
1771                         ar->ar_rc = rc;
1772
1773                 ar->ar_force_sync = 1;
1774                 ar->ar_min_xid = ptlrpc_sample_next_xid();
1775                 return;
1776
1777         }
1778
1779         if (ar->ar_force_sync && (xid >= ar->ar_min_xid))
1780                 ar->ar_force_sync = 0;
1781 }
1782
1783 /* Performs "unstable" page accounting. This function balances the
1784  * increment operations performed in osc_inc_unstable_pages. It is
1785  * registered as the RPC request callback, and is executed when the
1786  * bulk RPC is committed on the server. Thus at this point, the pages
1787  * involved in the bulk transfer are no longer considered unstable. */
1788 void osc_dec_unstable_pages(struct ptlrpc_request *req)
1789 {
1790         struct ptlrpc_bulk_desc *desc       = req->rq_bulk;
1791         struct client_obd       *cli        = &req->rq_import->imp_obd->u.cli;
1792         obd_count                page_count = desc->bd_iov_count;
1793         int i;
1794
1795         /* No unstable page tracking */
1796         if (cli->cl_cache == NULL)
1797                 return;
1798
1799         LASSERT(page_count >= 0);
1800
1801         for (i = 0; i < page_count; i++)
1802                 dec_zone_page_state(desc->bd_iov[i].kiov_page, NR_UNSTABLE_NFS);
1803
1804         cfs_atomic_sub(page_count, &cli->cl_cache->ccc_unstable_nr);
1805         LASSERT(cfs_atomic_read(&cli->cl_cache->ccc_unstable_nr) >= 0);
1806
1807         cfs_atomic_sub(page_count, &obd_unstable_pages);
1808         LASSERT(cfs_atomic_read(&obd_unstable_pages) >= 0);
1809
1810         spin_lock(&req->rq_lock);
1811         req->rq_committed = 1;
1812         req->rq_unstable  = 0;
1813         spin_unlock(&req->rq_lock);
1814
1815         wake_up_all(&cli->cl_cache->ccc_unstable_waitq);
1816 }
1817
1818 /* "unstable" page accounting. See: osc_dec_unstable_pages. */
1819 void osc_inc_unstable_pages(struct ptlrpc_request *req)
1820 {
1821         struct ptlrpc_bulk_desc *desc = req->rq_bulk;
1822         struct client_obd       *cli  = &req->rq_import->imp_obd->u.cli;
1823         obd_count                page_count = desc->bd_iov_count;
1824         int i;
1825
1826         /* No unstable page tracking */
1827         if (cli->cl_cache == NULL)
1828                 return;
1829
1830         LASSERT(page_count >= 0);
1831
1832         for (i = 0; i < page_count; i++)
1833                 inc_zone_page_state(desc->bd_iov[i].kiov_page, NR_UNSTABLE_NFS);
1834
1835         LASSERT(cfs_atomic_read(&cli->cl_cache->ccc_unstable_nr) >= 0);
1836         cfs_atomic_add(page_count, &cli->cl_cache->ccc_unstable_nr);
1837
1838         LASSERT(cfs_atomic_read(&obd_unstable_pages) >= 0);
1839         cfs_atomic_add(page_count, &obd_unstable_pages);
1840
1841         spin_lock(&req->rq_lock);
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. Otherwise, just set the commit callback so the
1847          * unstable page accounting is properly updated when the request
1848          * is committed */
1849         if (req->rq_committed) {
1850                 /* Drop lock before calling osc_dec_unstable_pages */
1851                 spin_unlock(&req->rq_lock);
1852                 osc_dec_unstable_pages(req);
1853                 spin_lock(&req->rq_lock);
1854         } else {
1855                 req->rq_unstable  = 1;
1856                 req->rq_commit_cb = osc_dec_unstable_pages;
1857         }
1858
1859         spin_unlock(&req->rq_lock);
1860 }
1861
1862 /* this must be called holding the loi list lock to give coverage to exit_cache,
1863  * async_flag maintenance, and oap_request */
1864 static void osc_ap_completion(const struct lu_env *env, struct client_obd *cli,
1865                               struct osc_async_page *oap, int sent, int rc)
1866 {
1867         struct osc_object *osc = oap->oap_obj;
1868         struct lov_oinfo  *loi = osc->oo_oinfo;
1869         __u64 xid = 0;
1870
1871         ENTRY;
1872         if (oap->oap_request != NULL) {
1873                 if (rc == 0)
1874                         osc_inc_unstable_pages(oap->oap_request);
1875
1876                 xid = ptlrpc_req_xid(oap->oap_request);
1877                 ptlrpc_req_finished(oap->oap_request);
1878                 oap->oap_request = NULL;
1879         }
1880
1881         /* As the transfer for this page is being done, clear the flags */
1882         spin_lock(&oap->oap_lock);
1883         oap->oap_async_flags = 0;
1884         spin_unlock(&oap->oap_lock);
1885         oap->oap_interrupted = 0;
1886
1887         if (oap->oap_cmd & OBD_BRW_WRITE && xid > 0) {
1888                 client_obd_list_lock(&cli->cl_loi_list_lock);
1889                 osc_process_ar(&cli->cl_ar, xid, rc);
1890                 osc_process_ar(&loi->loi_ar, xid, rc);
1891                 client_obd_list_unlock(&cli->cl_loi_list_lock);
1892         }
1893
1894         rc = osc_completion(env, oap, oap->oap_cmd, rc);
1895         if (rc)
1896                 CERROR("completion on oap %p obj %p returns %d.\n",
1897                        oap, osc, rc);
1898
1899         EXIT;
1900 }
1901
1902 /**
1903  * Try to add extent to one RPC. We need to think about the following things:
1904  * - # of pages must not be over max_pages_per_rpc
1905  * - extent must be compatible with previous ones
1906  */
1907 static int try_to_add_extent_for_io(struct client_obd *cli,
1908                                     struct osc_extent *ext, cfs_list_t *rpclist,
1909                                     int *pc, unsigned int *max_pages)
1910 {
1911         struct osc_extent *tmp;
1912         ENTRY;
1913
1914         EASSERT((ext->oe_state == OES_CACHE || ext->oe_state == OES_LOCK_DONE),
1915                 ext);
1916
1917         *max_pages = max(ext->oe_mppr, *max_pages);
1918         if (*pc + ext->oe_nr_pages > *max_pages)
1919                 RETURN(0);
1920
1921         cfs_list_for_each_entry(tmp, rpclist, oe_link) {
1922                 EASSERT(tmp->oe_owner == current, tmp);
1923 #if 0
1924                 if (overlapped(tmp, ext)) {
1925                         OSC_EXTENT_DUMP(D_ERROR, tmp, "overlapped %p.\n", ext);
1926                         EASSERT(0, ext);
1927                 }
1928 #endif
1929
1930                 if (tmp->oe_srvlock != ext->oe_srvlock ||
1931                     !tmp->oe_grants != !ext->oe_grants)
1932                         RETURN(0);
1933
1934                 /* remove break for strict check */
1935                 break;
1936         }
1937
1938         *pc += ext->oe_nr_pages;
1939         cfs_list_move_tail(&ext->oe_link, rpclist);
1940         ext->oe_owner = current;
1941         RETURN(1);
1942 }
1943
1944 /**
1945  * In order to prevent multiple ptlrpcd from breaking contiguous extents,
1946  * get_write_extent() takes all appropriate extents in atomic.
1947  *
1948  * The following policy is used to collect extents for IO:
1949  * 1. Add as many HP extents as possible;
1950  * 2. Add the first urgent extent in urgent extent list and take it out of
1951  *    urgent list;
1952  * 3. Add subsequent extents of this urgent extent;
1953  * 4. If urgent list is not empty, goto 2;
1954  * 5. Traverse the extent tree from the 1st extent;
1955  * 6. Above steps exit if there is no space in this RPC.
1956  */
1957 static int get_write_extents(struct osc_object *obj, cfs_list_t *rpclist)
1958 {
1959         struct client_obd *cli = osc_cli(obj);
1960         struct osc_extent *ext;
1961         int page_count = 0;
1962         unsigned int max_pages = cli->cl_max_pages_per_rpc;
1963
1964         LASSERT(osc_object_is_locked(obj));
1965         while (!cfs_list_empty(&obj->oo_hp_exts)) {
1966                 ext = cfs_list_entry(obj->oo_hp_exts.next, struct osc_extent,
1967                                      oe_link);
1968                 LASSERT(ext->oe_state == OES_CACHE);
1969                 if (!try_to_add_extent_for_io(cli, ext, rpclist, &page_count,
1970                                               &max_pages))
1971                         return page_count;
1972                 EASSERT(ext->oe_nr_pages <= max_pages, ext);
1973         }
1974         if (page_count == max_pages)
1975                 return page_count;
1976
1977         while (!cfs_list_empty(&obj->oo_urgent_exts)) {
1978                 ext = cfs_list_entry(obj->oo_urgent_exts.next,
1979                                      struct osc_extent, oe_link);
1980                 if (!try_to_add_extent_for_io(cli, ext, rpclist, &page_count,
1981                                               &max_pages))
1982                         return page_count;
1983
1984                 if (!ext->oe_intree)
1985                         continue;
1986
1987                 while ((ext = next_extent(ext)) != NULL) {
1988                         if ((ext->oe_state != OES_CACHE) ||
1989                             (!cfs_list_empty(&ext->oe_link) &&
1990                              ext->oe_owner != NULL))
1991                                 continue;
1992
1993                         if (!try_to_add_extent_for_io(cli, ext, rpclist,
1994                                                       &page_count, &max_pages))
1995                                 return page_count;
1996                 }
1997         }
1998         if (page_count == max_pages)
1999                 return page_count;
2000
2001         ext = first_extent(obj);
2002         while (ext != NULL) {
2003                 if ((ext->oe_state != OES_CACHE) ||
2004                     /* this extent may be already in current rpclist */
2005                     (!cfs_list_empty(&ext->oe_link) && ext->oe_owner != NULL)) {
2006                         ext = next_extent(ext);
2007                         continue;
2008                 }
2009
2010                 if (!try_to_add_extent_for_io(cli, ext, rpclist, &page_count,
2011                                               &max_pages))
2012                         return page_count;
2013
2014                 ext = next_extent(ext);
2015         }
2016         return page_count;
2017 }
2018
2019 static int
2020 osc_send_write_rpc(const struct lu_env *env, struct client_obd *cli,
2021                    struct osc_object *osc, pdl_policy_t pol)
2022 {
2023         CFS_LIST_HEAD(rpclist);
2024         struct osc_extent *ext;
2025         struct osc_extent *tmp;
2026         struct osc_extent *first = NULL;
2027         obd_count page_count = 0;
2028         int srvlock = 0;
2029         int rc = 0;
2030         ENTRY;
2031
2032         LASSERT(osc_object_is_locked(osc));
2033
2034         page_count = get_write_extents(osc, &rpclist);
2035         LASSERT(equi(page_count == 0, cfs_list_empty(&rpclist)));
2036
2037         if (cfs_list_empty(&rpclist))
2038                 RETURN(0);
2039
2040         osc_update_pending(osc, OBD_BRW_WRITE, -page_count);
2041
2042         cfs_list_for_each_entry(ext, &rpclist, oe_link) {
2043                 LASSERT(ext->oe_state == OES_CACHE ||
2044                         ext->oe_state == OES_LOCK_DONE);
2045                 if (ext->oe_state == OES_CACHE)
2046                         osc_extent_state_set(ext, OES_LOCKING);
2047                 else
2048                         osc_extent_state_set(ext, OES_RPC);
2049         }
2050
2051         /* we're going to grab page lock, so release object lock because
2052          * lock order is page lock -> object lock. */
2053         osc_object_unlock(osc);
2054
2055         cfs_list_for_each_entry_safe(ext, tmp, &rpclist, oe_link) {
2056                 if (ext->oe_state == OES_LOCKING) {
2057                         rc = osc_extent_make_ready(env, ext);
2058                         if (unlikely(rc < 0)) {
2059                                 cfs_list_del_init(&ext->oe_link);
2060                                 osc_extent_finish(env, ext, 0, rc);
2061                                 continue;
2062                         }
2063                 }
2064                 if (first == NULL) {
2065                         first = ext;
2066                         srvlock = ext->oe_srvlock;
2067                 } else {
2068                         LASSERT(srvlock == ext->oe_srvlock);
2069                 }
2070         }
2071
2072         if (!cfs_list_empty(&rpclist)) {
2073                 LASSERT(page_count > 0);
2074                 rc = osc_build_rpc(env, cli, &rpclist, OBD_BRW_WRITE, pol);
2075                 LASSERT(cfs_list_empty(&rpclist));
2076         }
2077
2078         osc_object_lock(osc);
2079         RETURN(rc);
2080 }
2081
2082 /**
2083  * prepare pages for ASYNC io and put pages in send queue.
2084  *
2085  * \param cmd OBD_BRW_* macroses
2086  * \param lop pending pages
2087  *
2088  * \return zero if no page added to send queue.
2089  * \return 1 if pages successfully added to send queue.
2090  * \return negative on errors.
2091  */
2092 static int
2093 osc_send_read_rpc(const struct lu_env *env, struct client_obd *cli,
2094                   struct osc_object *osc, pdl_policy_t pol)
2095 {
2096         struct osc_extent *ext;
2097         struct osc_extent *next;
2098         CFS_LIST_HEAD(rpclist);
2099         int page_count = 0;
2100         unsigned int max_pages = cli->cl_max_pages_per_rpc;
2101         int rc = 0;
2102         ENTRY;
2103
2104         LASSERT(osc_object_is_locked(osc));
2105         cfs_list_for_each_entry_safe(ext, next,
2106                                      &osc->oo_reading_exts, oe_link) {
2107                 EASSERT(ext->oe_state == OES_LOCK_DONE, ext);
2108                 if (!try_to_add_extent_for_io(cli, ext, &rpclist, &page_count,
2109                                               &max_pages))
2110                         break;
2111                 osc_extent_state_set(ext, OES_RPC);
2112                 EASSERT(ext->oe_nr_pages <= max_pages, ext);
2113         }
2114         LASSERT(page_count <= max_pages);
2115
2116         osc_update_pending(osc, OBD_BRW_READ, -page_count);
2117
2118         if (!cfs_list_empty(&rpclist)) {
2119                 osc_object_unlock(osc);
2120
2121                 LASSERT(page_count > 0);
2122                 rc = osc_build_rpc(env, cli, &rpclist, OBD_BRW_READ, pol);
2123                 LASSERT(cfs_list_empty(&rpclist));
2124
2125                 osc_object_lock(osc);
2126         }
2127         RETURN(rc);
2128 }
2129
2130 #define list_to_obj(list, item) ({                                            \
2131         cfs_list_t *__tmp = (list)->next;                                     \
2132         cfs_list_del_init(__tmp);                                             \
2133         cfs_list_entry(__tmp, struct osc_object, oo_##item);                  \
2134 })
2135
2136 /* This is called by osc_check_rpcs() to find which objects have pages that
2137  * we could be sending.  These lists are maintained by osc_makes_rpc(). */
2138 static struct osc_object *osc_next_obj(struct client_obd *cli)
2139 {
2140         ENTRY;
2141
2142         /* First return objects that have blocked locks so that they
2143          * will be flushed quickly and other clients can get the lock,
2144          * then objects which have pages ready to be stuffed into RPCs */
2145         if (!cfs_list_empty(&cli->cl_loi_hp_ready_list))
2146                 RETURN(list_to_obj(&cli->cl_loi_hp_ready_list, hp_ready_item));
2147         if (!cfs_list_empty(&cli->cl_loi_ready_list))
2148                 RETURN(list_to_obj(&cli->cl_loi_ready_list, ready_item));
2149
2150         /* then if we have cache waiters, return all objects with queued
2151          * writes.  This is especially important when many small files
2152          * have filled up the cache and not been fired into rpcs because
2153          * they don't pass the nr_pending/object threshhold */
2154         if (!cfs_list_empty(&cli->cl_cache_waiters) &&
2155             !cfs_list_empty(&cli->cl_loi_write_list))
2156                 RETURN(list_to_obj(&cli->cl_loi_write_list, write_item));
2157
2158         /* then return all queued objects when we have an invalid import
2159          * so that they get flushed */
2160         if (cli->cl_import == NULL || cli->cl_import->imp_invalid) {
2161                 if (!cfs_list_empty(&cli->cl_loi_write_list))
2162                         RETURN(list_to_obj(&cli->cl_loi_write_list,
2163                                            write_item));
2164                 if (!cfs_list_empty(&cli->cl_loi_read_list))
2165                         RETURN(list_to_obj(&cli->cl_loi_read_list,
2166                                            read_item));
2167         }
2168         RETURN(NULL);
2169 }
2170
2171 /* called with the loi list lock held */
2172 static void osc_check_rpcs(const struct lu_env *env, struct client_obd *cli,
2173                            pdl_policy_t pol)
2174 {
2175         struct osc_object *osc;
2176         int rc = 0;
2177         ENTRY;
2178
2179         while ((osc = osc_next_obj(cli)) != NULL) {
2180                 struct cl_object *obj = osc2cl(osc);
2181                 struct lu_ref_link link;
2182
2183                 OSC_IO_DEBUG(osc, "%lu in flight\n", rpcs_in_flight(cli));
2184
2185                 if (osc_max_rpc_in_flight(cli, osc)) {
2186                         __osc_list_maint(cli, osc);
2187                         break;
2188                 }
2189
2190                 cl_object_get(obj);
2191                 client_obd_list_unlock(&cli->cl_loi_list_lock);
2192                 lu_object_ref_add_at(&obj->co_lu, &link, "check",
2193                                      current);
2194
2195                 /* attempt some read/write balancing by alternating between
2196                  * reads and writes in an object.  The makes_rpc checks here
2197                  * would be redundant if we were getting read/write work items
2198                  * instead of objects.  we don't want send_oap_rpc to drain a
2199                  * partial read pending queue when we're given this object to
2200                  * do io on writes while there are cache waiters */
2201                 osc_object_lock(osc);
2202                 if (osc_makes_rpc(cli, osc, OBD_BRW_WRITE)) {
2203                         rc = osc_send_write_rpc(env, cli, osc, pol);
2204                         if (rc < 0) {
2205                                 CERROR("Write request failed with %d\n", rc);
2206
2207                                 /* osc_send_write_rpc failed, mostly because of
2208                                  * memory pressure.
2209                                  *
2210                                  * It can't break here, because if:
2211                                  *  - a page was submitted by osc_io_submit, so
2212                                  *    page locked;
2213                                  *  - no request in flight
2214                                  *  - no subsequent request
2215                                  * The system will be in live-lock state,
2216                                  * because there is no chance to call
2217                                  * osc_io_unplug() and osc_check_rpcs() any
2218                                  * more. pdflush can't help in this case,
2219                                  * because it might be blocked at grabbing
2220                                  * the page lock as we mentioned.
2221                                  *
2222                                  * Anyway, continue to drain pages. */
2223                                 /* break; */
2224                         }
2225                 }
2226                 if (osc_makes_rpc(cli, osc, OBD_BRW_READ)) {
2227                         rc = osc_send_read_rpc(env, cli, osc, pol);
2228                         if (rc < 0)
2229                                 CERROR("Read request failed with %d\n", rc);
2230                 }
2231                 osc_object_unlock(osc);
2232
2233                 osc_list_maint(cli, osc);
2234                 lu_object_ref_del_at(&obj->co_lu, &link, "check",
2235                                      current);
2236                 cl_object_put(env, obj);
2237
2238                 client_obd_list_lock(&cli->cl_loi_list_lock);
2239         }
2240 }
2241
2242 static int osc_io_unplug0(const struct lu_env *env, struct client_obd *cli,
2243                           struct osc_object *osc, pdl_policy_t pol, int async)
2244 {
2245         int rc = 0;
2246
2247         if (osc != NULL && osc_list_maint(cli, osc) == 0)
2248                 return 0;
2249
2250         if (!async) {
2251                 /* disable osc_lru_shrink() temporarily to avoid
2252                  * potential stack overrun problem. LU-2859 */
2253                 cfs_atomic_inc(&cli->cl_lru_shrinkers);
2254                 client_obd_list_lock(&cli->cl_loi_list_lock);
2255                 osc_check_rpcs(env, cli, pol);
2256                 client_obd_list_unlock(&cli->cl_loi_list_lock);
2257                 cfs_atomic_dec(&cli->cl_lru_shrinkers);
2258         } else {
2259                 CDEBUG(D_CACHE, "Queue writeback work for client %p.\n", cli);
2260                 LASSERT(cli->cl_writeback_work != NULL);
2261                 rc = ptlrpcd_queue_work(cli->cl_writeback_work);
2262         }
2263         return rc;
2264 }
2265
2266 static int osc_io_unplug_async(const struct lu_env *env,
2267                                 struct client_obd *cli, struct osc_object *osc)
2268 {
2269         /* XXX: policy is no use actually. */
2270         return osc_io_unplug0(env, cli, osc, PDL_POLICY_ROUND, 1);
2271 }
2272
2273 void osc_io_unplug(const struct lu_env *env, struct client_obd *cli,
2274                    struct osc_object *osc, pdl_policy_t pol)
2275 {
2276         (void)osc_io_unplug0(env, cli, osc, pol, 0);
2277 }
2278
2279 int osc_prep_async_page(struct osc_object *osc, struct osc_page *ops,
2280                         struct page *page, loff_t offset)
2281 {
2282         struct obd_export     *exp = osc_export(osc);
2283         struct osc_async_page *oap = &ops->ops_oap;
2284         ENTRY;
2285
2286         if (!page)
2287                 return cfs_size_round(sizeof(*oap));
2288
2289         oap->oap_magic = OAP_MAGIC;
2290         oap->oap_cli = &exp->exp_obd->u.cli;
2291         oap->oap_obj = osc;
2292
2293         oap->oap_page = page;
2294         oap->oap_obj_off = offset;
2295         LASSERT(!(offset & ~CFS_PAGE_MASK));
2296
2297         if (!client_is_remote(exp) && cfs_capable(CFS_CAP_SYS_RESOURCE))
2298                 oap->oap_brw_flags = OBD_BRW_NOQUOTA;
2299
2300         CFS_INIT_LIST_HEAD(&oap->oap_pending_item);
2301         CFS_INIT_LIST_HEAD(&oap->oap_rpc_item);
2302
2303         spin_lock_init(&oap->oap_lock);
2304         CDEBUG(D_INFO, "oap %p page %p obj off "LPU64"\n",
2305                oap, page, oap->oap_obj_off);
2306         RETURN(0);
2307 }
2308
2309 int osc_queue_async_io(const struct lu_env *env, struct cl_io *io,
2310                        struct osc_page *ops)
2311 {
2312         struct osc_io *oio = osc_env_io(env);
2313         struct osc_extent     *ext = NULL;
2314         struct osc_async_page *oap = &ops->ops_oap;
2315         struct client_obd     *cli = oap->oap_cli;
2316         struct osc_object     *osc = oap->oap_obj;
2317         pgoff_t index;
2318         int    grants = 0;
2319         int    brw_flags = OBD_BRW_ASYNC;
2320         int    cmd = OBD_BRW_WRITE;
2321         int    need_release = 0;
2322         int    rc = 0;
2323         ENTRY;
2324
2325         if (oap->oap_magic != OAP_MAGIC)
2326                 RETURN(-EINVAL);
2327
2328         if (cli->cl_import == NULL || cli->cl_import->imp_invalid)
2329                 RETURN(-EIO);
2330
2331         if (!cfs_list_empty(&oap->oap_pending_item) ||
2332             !cfs_list_empty(&oap->oap_rpc_item))
2333                 RETURN(-EBUSY);
2334
2335         /* Set the OBD_BRW_SRVLOCK before the page is queued. */
2336         brw_flags |= ops->ops_srvlock ? OBD_BRW_SRVLOCK : 0;
2337         if (!client_is_remote(osc_export(osc)) &&
2338             cfs_capable(CFS_CAP_SYS_RESOURCE)) {
2339                 brw_flags |= OBD_BRW_NOQUOTA;
2340                 cmd |= OBD_BRW_NOQUOTA;
2341         }
2342
2343         /* check if the file's owner/group is over quota */
2344         if (!(cmd & OBD_BRW_NOQUOTA)) {
2345                 struct cl_object *obj;
2346                 struct cl_attr   *attr;
2347                 unsigned int qid[MAXQUOTAS];
2348
2349                 obj = cl_object_top(&osc->oo_cl);
2350                 attr = &osc_env_info(env)->oti_attr;
2351
2352                 cl_object_attr_lock(obj);
2353                 rc = cl_object_attr_get(env, obj, attr);
2354                 cl_object_attr_unlock(obj);
2355
2356                 qid[USRQUOTA] = attr->cat_uid;
2357                 qid[GRPQUOTA] = attr->cat_gid;
2358                 if (rc == 0 && osc_quota_chkdq(cli, qid) == NO_QUOTA)
2359                         rc = -EDQUOT;
2360                 if (rc)
2361                         RETURN(rc);
2362         }
2363
2364         oap->oap_cmd = cmd;
2365         oap->oap_page_off = ops->ops_from;
2366         oap->oap_count = ops->ops_to - ops->ops_from;
2367         /* No need to hold a lock here,
2368          * since this page is not in any list yet. */
2369         oap->oap_async_flags = 0;
2370         oap->oap_brw_flags = brw_flags;
2371
2372         OSC_IO_DEBUG(osc, "oap %p page %p added for cmd %d\n",
2373                      oap, oap->oap_page, oap->oap_cmd & OBD_BRW_RWMASK);
2374
2375         index = oap2cl_page(oap)->cp_index;
2376
2377         /* Add this page into extent by the following steps:
2378          * 1. if there exists an active extent for this IO, mostly this page
2379          *    can be added to the active extent and sometimes we need to
2380          *    expand extent to accomodate this page;
2381          * 2. otherwise, a new extent will be allocated. */
2382
2383         ext = oio->oi_active;
2384         if (ext != NULL && ext->oe_start <= index && ext->oe_max_end >= index) {
2385                 /* one chunk plus extent overhead must be enough to write this
2386                  * page */
2387                 grants = (1 << cli->cl_chunkbits) + cli->cl_extent_tax;
2388                 if (ext->oe_end >= index)
2389                         grants = 0;
2390
2391                 /* it doesn't need any grant to dirty this page */
2392                 client_obd_list_lock(&cli->cl_loi_list_lock);
2393                 rc = osc_enter_cache_try(cli, oap, grants, 0);
2394                 client_obd_list_unlock(&cli->cl_loi_list_lock);
2395                 if (rc == 0) { /* try failed */
2396                         grants = 0;
2397                         need_release = 1;
2398                 } else if (ext->oe_end < index) {
2399                         int tmp = grants;
2400                         /* try to expand this extent */
2401                         rc = osc_extent_expand(ext, index, &tmp);
2402                         if (rc < 0) {
2403                                 need_release = 1;
2404                                 /* don't free reserved grant */
2405                         } else {
2406                                 OSC_EXTENT_DUMP(D_CACHE, ext,
2407                                                 "expanded for %lu.\n", index);
2408                                 osc_unreserve_grant(cli, grants, tmp);
2409                                 grants = 0;
2410                         }
2411                 }
2412                 rc = 0;
2413         } else if (ext != NULL) {
2414                 /* index is located outside of active extent */
2415                 need_release = 1;
2416         }
2417         if (need_release) {
2418                 osc_extent_release(env, ext);
2419                 oio->oi_active = NULL;
2420                 ext = NULL;
2421         }
2422
2423         if (ext == NULL) {
2424                 int tmp = (1 << cli->cl_chunkbits) + cli->cl_extent_tax;
2425
2426                 /* try to find new extent to cover this page */
2427                 LASSERT(oio->oi_active == NULL);
2428                 /* we may have allocated grant for this page if we failed
2429                  * to expand the previous active extent. */
2430                 LASSERT(ergo(grants > 0, grants >= tmp));
2431
2432                 rc = 0;
2433                 if (grants == 0) {
2434                         /* we haven't allocated grant for this page. */
2435                         rc = osc_enter_cache(env, cli, oap, tmp);
2436                         if (rc == 0)
2437                                 grants = tmp;
2438                 }
2439
2440                 tmp = grants;
2441                 if (rc == 0) {
2442                         ext = osc_extent_find(env, osc, index, &tmp);
2443                         if (IS_ERR(ext)) {
2444                                 LASSERT(tmp == grants);
2445                                 osc_exit_cache(cli, oap);
2446                                 rc = PTR_ERR(ext);
2447                                 ext = NULL;
2448                         } else {
2449                                 oio->oi_active = ext;
2450                         }
2451                 }
2452                 if (grants > 0)
2453                         osc_unreserve_grant(cli, grants, tmp);
2454         }
2455
2456         LASSERT(ergo(rc == 0, ext != NULL));
2457         if (ext != NULL) {
2458                 EASSERTF(ext->oe_end >= index && ext->oe_start <= index,
2459                          ext, "index = %lu.\n", index);
2460                 LASSERT((oap->oap_brw_flags & OBD_BRW_FROM_GRANT) != 0);
2461
2462                 osc_object_lock(osc);
2463                 if (ext->oe_nr_pages == 0)
2464                         ext->oe_srvlock = ops->ops_srvlock;
2465                 else
2466                         LASSERT(ext->oe_srvlock == ops->ops_srvlock);
2467                 ++ext->oe_nr_pages;
2468                 cfs_list_add_tail(&oap->oap_pending_item, &ext->oe_pages);
2469                 osc_object_unlock(osc);
2470         }
2471         RETURN(rc);
2472 }
2473
2474 int osc_teardown_async_page(const struct lu_env *env,
2475                             struct osc_object *obj, struct osc_page *ops)
2476 {
2477         struct osc_async_page *oap = &ops->ops_oap;
2478         struct osc_extent     *ext = NULL;
2479         int rc = 0;
2480         ENTRY;
2481
2482         LASSERT(oap->oap_magic == OAP_MAGIC);
2483
2484         CDEBUG(D_INFO, "teardown oap %p page %p at index %lu.\n",
2485                oap, ops, oap2cl_page(oap)->cp_index);
2486
2487         osc_object_lock(obj);
2488         if (!cfs_list_empty(&oap->oap_rpc_item)) {
2489                 CDEBUG(D_CACHE, "oap %p is not in cache.\n", oap);
2490                 rc = -EBUSY;
2491         } else if (!cfs_list_empty(&oap->oap_pending_item)) {
2492                 ext = osc_extent_lookup(obj, oap2cl_page(oap)->cp_index);
2493                 /* only truncated pages are allowed to be taken out.
2494                  * See osc_extent_truncate() and osc_cache_truncate_start()
2495                  * for details. */
2496                 if (ext != NULL && ext->oe_state != OES_TRUNC) {
2497                         OSC_EXTENT_DUMP(D_ERROR, ext, "trunc at %lu.\n",
2498                                         oap2cl_page(oap)->cp_index);
2499                         rc = -EBUSY;
2500                 }
2501         }
2502         osc_object_unlock(obj);
2503         if (ext != NULL)
2504                 osc_extent_put(env, ext);
2505         RETURN(rc);
2506 }
2507
2508 /**
2509  * This is called when a page is picked up by kernel to write out.
2510  *
2511  * We should find out the corresponding extent and add the whole extent
2512  * into urgent list. The extent may be being truncated or used, handle it
2513  * carefully.
2514  */
2515 int osc_flush_async_page(const struct lu_env *env, struct cl_io *io,
2516                          struct osc_page *ops)
2517 {
2518         struct osc_extent *ext   = NULL;
2519         struct osc_object *obj   = cl2osc(ops->ops_cl.cpl_obj);
2520         struct cl_page    *cp    = ops->ops_cl.cpl_page;
2521         pgoff_t            index = cp->cp_index;
2522         struct osc_async_page *oap = &ops->ops_oap;
2523         bool unplug = false;
2524         int rc = 0;
2525         ENTRY;
2526
2527         osc_object_lock(obj);
2528         ext = osc_extent_lookup(obj, index);
2529         if (ext == NULL) {
2530                 osc_extent_tree_dump(D_ERROR, obj);
2531                 LASSERTF(0, "page index %lu is NOT covered.\n", index);
2532         }
2533
2534         switch (ext->oe_state) {
2535         case OES_RPC:
2536         case OES_LOCK_DONE:
2537                 CL_PAGE_DEBUG(D_ERROR, env, cl_page_top(cp),
2538                               "flush an in-rpc page?\n");
2539                 LASSERT(0);
2540                 break;
2541         case OES_LOCKING:
2542                 /* If we know this extent is being written out, we should abort
2543                  * so that the writer can make this page ready. Otherwise, there
2544                  * exists a deadlock problem because other process can wait for
2545                  * page writeback bit holding page lock; and meanwhile in
2546                  * vvp_page_make_ready(), we need to grab page lock before
2547                  * really sending the RPC. */
2548         case OES_TRUNC:
2549                 /* race with truncate, page will be redirtied */
2550                 GOTO(out, rc = -EAGAIN);
2551         default:
2552                 break;
2553         }
2554
2555         rc = cl_page_prep(env, io, cl_page_top(cp), CRT_WRITE);
2556         if (rc)
2557                 GOTO(out, rc);
2558
2559         spin_lock(&oap->oap_lock);
2560         oap->oap_async_flags |= ASYNC_READY|ASYNC_URGENT;
2561         spin_unlock(&oap->oap_lock);
2562
2563         if (memory_pressure_get())
2564                 ext->oe_memalloc = 1;
2565
2566         ext->oe_urgent = 1;
2567         if (ext->oe_state == OES_CACHE) {
2568                 OSC_EXTENT_DUMP(D_CACHE, ext,
2569                                 "flush page %p make it urgent.\n", oap);
2570                 if (cfs_list_empty(&ext->oe_link))
2571                         cfs_list_add_tail(&ext->oe_link, &obj->oo_urgent_exts);
2572                 unplug = true;
2573         }
2574         rc = 0;
2575         EXIT;
2576
2577 out:
2578         osc_object_unlock(obj);
2579         osc_extent_put(env, ext);
2580         if (unplug)
2581                 osc_io_unplug_async(env, osc_cli(obj), obj);
2582         return rc;
2583 }
2584
2585 /**
2586  * this is called when a sync waiter receives an interruption.  Its job is to
2587  * get the caller woken as soon as possible.  If its page hasn't been put in an
2588  * rpc yet it can dequeue immediately.  Otherwise it has to mark the rpc as
2589  * desiring interruption which will forcefully complete the rpc once the rpc
2590  * has timed out.
2591  */
2592 int osc_cancel_async_page(const struct lu_env *env, struct osc_page *ops)
2593 {
2594         struct osc_async_page *oap = &ops->ops_oap;
2595         struct osc_object     *obj = oap->oap_obj;
2596         struct client_obd     *cli = osc_cli(obj);
2597         struct osc_extent     *ext;
2598         struct osc_extent     *found = NULL;
2599         cfs_list_t            *plist;
2600         pgoff_t index = oap2cl_page(oap)->cp_index;
2601         int     rc = -EBUSY;
2602         int     cmd;
2603         ENTRY;
2604
2605         LASSERT(!oap->oap_interrupted);
2606         oap->oap_interrupted = 1;
2607
2608         /* Find out the caching extent */
2609         osc_object_lock(obj);
2610         if (oap->oap_cmd & OBD_BRW_WRITE) {
2611                 plist = &obj->oo_urgent_exts;
2612                 cmd   = OBD_BRW_WRITE;
2613         } else {
2614                 plist = &obj->oo_reading_exts;
2615                 cmd   = OBD_BRW_READ;
2616         }
2617         cfs_list_for_each_entry(ext, plist, oe_link) {
2618                 if (ext->oe_start <= index && ext->oe_end >= index) {
2619                         LASSERT(ext->oe_state == OES_LOCK_DONE);
2620                         /* For OES_LOCK_DONE state extent, it has already held
2621                          * a refcount for RPC. */
2622                         found = osc_extent_get(ext);
2623                         break;
2624                 }
2625         }
2626         if (found != NULL) {
2627                 cfs_list_del_init(&found->oe_link);
2628                 osc_update_pending(obj, cmd, -found->oe_nr_pages);
2629                 osc_object_unlock(obj);
2630
2631                 osc_extent_finish(env, found, 0, -EINTR);
2632                 osc_extent_put(env, found);
2633                 rc = 0;
2634         } else {
2635                 osc_object_unlock(obj);
2636                 /* ok, it's been put in an rpc. only one oap gets a request
2637                  * reference */
2638                 if (oap->oap_request != NULL) {
2639                         ptlrpc_mark_interrupted(oap->oap_request);
2640                         ptlrpcd_wake(oap->oap_request);
2641                         ptlrpc_req_finished(oap->oap_request);
2642                         oap->oap_request = NULL;
2643                 }
2644         }
2645
2646         osc_list_maint(cli, obj);
2647         RETURN(rc);
2648 }
2649
2650 int osc_queue_sync_pages(const struct lu_env *env, struct osc_object *obj,
2651                          cfs_list_t *list, int cmd, int brw_flags)
2652 {
2653         struct client_obd     *cli = osc_cli(obj);
2654         struct osc_extent     *ext;
2655         struct osc_async_page *oap;
2656         int     page_count = 0;
2657         int     mppr       = cli->cl_max_pages_per_rpc;
2658         pgoff_t start      = CL_PAGE_EOF;
2659         pgoff_t end        = 0;
2660         ENTRY;
2661
2662         cfs_list_for_each_entry(oap, list, oap_pending_item) {
2663                 struct cl_page *cp = oap2cl_page(oap);
2664                 if (cp->cp_index > end)
2665                         end = cp->cp_index;
2666                 if (cp->cp_index < start)
2667                         start = cp->cp_index;
2668                 ++page_count;
2669                 mppr <<= (page_count > mppr);
2670         }
2671
2672         ext = osc_extent_alloc(obj);
2673         if (ext == NULL) {
2674                 cfs_list_for_each_entry(oap, list, oap_pending_item) {
2675                         cfs_list_del_init(&oap->oap_pending_item);
2676                         osc_ap_completion(env, cli, oap, 0, -ENOMEM);
2677                 }
2678                 RETURN(-ENOMEM);
2679         }
2680
2681         ext->oe_rw = !!(cmd & OBD_BRW_READ);
2682         ext->oe_urgent = 1;
2683         ext->oe_start = start;
2684         ext->oe_end = ext->oe_max_end = end;
2685         ext->oe_obj = obj;
2686         ext->oe_srvlock = !!(brw_flags & OBD_BRW_SRVLOCK);
2687         ext->oe_nr_pages = page_count;
2688         ext->oe_mppr = mppr;
2689         cfs_list_splice_init(list, &ext->oe_pages);
2690
2691         osc_object_lock(obj);
2692         /* Reuse the initial refcount for RPC, don't drop it */
2693         osc_extent_state_set(ext, OES_LOCK_DONE);
2694         if (cmd & OBD_BRW_WRITE) {
2695                 cfs_list_add_tail(&ext->oe_link, &obj->oo_urgent_exts);
2696                 osc_update_pending(obj, OBD_BRW_WRITE, page_count);
2697         } else {
2698                 cfs_list_add_tail(&ext->oe_link, &obj->oo_reading_exts);
2699                 osc_update_pending(obj, OBD_BRW_READ, page_count);
2700         }
2701         osc_object_unlock(obj);
2702
2703         osc_io_unplug(env, cli, obj, PDL_POLICY_ROUND);
2704         RETURN(0);
2705 }
2706
2707 /**
2708  * Called by osc_io_setattr_start() to freeze and destroy covering extents.
2709  */
2710 int osc_cache_truncate_start(const struct lu_env *env, struct osc_io *oio,
2711                              struct osc_object *obj, __u64 size)
2712 {
2713         struct client_obd *cli = osc_cli(obj);
2714         struct osc_extent *ext;
2715         struct osc_extent *waiting = NULL;
2716         pgoff_t index;
2717         CFS_LIST_HEAD(list);
2718         int result = 0;
2719         bool partial;
2720         ENTRY;
2721
2722         /* pages with index greater or equal to index will be truncated. */
2723         index = cl_index(osc2cl(obj), size);
2724         partial = size > cl_offset(osc2cl(obj), index);
2725
2726 again:
2727         osc_object_lock(obj);
2728         ext = osc_extent_search(obj, index);
2729         if (ext == NULL)
2730                 ext = first_extent(obj);
2731         else if (ext->oe_end < index)
2732                 ext = next_extent(ext);
2733         while (ext != NULL) {
2734                 EASSERT(ext->oe_state != OES_TRUNC, ext);
2735
2736                 if (ext->oe_state > OES_CACHE || ext->oe_urgent) {
2737                         /* if ext is in urgent state, it means there must exist
2738                          * a page already having been flushed by write_page().
2739                          * We have to wait for this extent because we can't
2740                          * truncate that page. */
2741                         LASSERT(!ext->oe_hp);
2742                         OSC_EXTENT_DUMP(D_CACHE, ext,
2743                                         "waiting for busy extent\n");
2744                         waiting = osc_extent_get(ext);
2745                         break;
2746                 }
2747
2748                 OSC_EXTENT_DUMP(D_CACHE, ext, "try to trunc:"LPU64".\n", size);
2749
2750                 osc_extent_get(ext);
2751                 if (ext->oe_state == OES_ACTIVE) {
2752                         /* though we grab inode mutex for write path, but we
2753                          * release it before releasing extent(in osc_io_end()),
2754                          * so there is a race window that an extent is still
2755                          * in OES_ACTIVE when truncate starts. */
2756                         LASSERT(!ext->oe_trunc_pending);
2757                         ext->oe_trunc_pending = 1;
2758                 } else {
2759                         EASSERT(ext->oe_state == OES_CACHE, ext);
2760                         osc_extent_state_set(ext, OES_TRUNC);
2761                         osc_update_pending(obj, OBD_BRW_WRITE,
2762                                            -ext->oe_nr_pages);
2763                 }
2764                 EASSERT(cfs_list_empty(&ext->oe_link), ext);
2765                 cfs_list_add_tail(&ext->oe_link, &list);
2766
2767                 ext = next_extent(ext);
2768         }
2769         osc_object_unlock(obj);
2770
2771         osc_list_maint(cli, obj);
2772
2773         while (!cfs_list_empty(&list)) {
2774                 int rc;
2775
2776                 ext = cfs_list_entry(list.next, struct osc_extent, oe_link);
2777                 cfs_list_del_init(&ext->oe_link);
2778
2779                 /* extent may be in OES_ACTIVE state because inode mutex
2780                  * is released before osc_io_end() in file write case */
2781                 if (ext->oe_state != OES_TRUNC)
2782                         osc_extent_wait(env, ext, OES_TRUNC);
2783
2784                 rc = osc_extent_truncate(ext, index, partial);
2785                 if (rc < 0) {
2786                         if (result == 0)
2787                                 result = rc;
2788
2789                         OSC_EXTENT_DUMP(D_ERROR, ext,
2790                                         "truncate error %d\n", rc);
2791                 } else if (ext->oe_nr_pages == 0) {
2792                         osc_extent_remove(ext);
2793                 } else {
2794                         /* this must be an overlapped extent which means only
2795                          * part of pages in this extent have been truncated.
2796                          */
2797                         EASSERTF(ext->oe_start <= index, ext,
2798                                  "trunc index = %lu/%d.\n", index, partial);
2799                         /* fix index to skip this partially truncated extent */
2800                         index = ext->oe_end + 1;
2801                         partial = false;
2802
2803                         /* we need to hold this extent in OES_TRUNC state so
2804                          * that no writeback will happen. This is to avoid
2805                          * BUG 17397. */
2806                         LASSERT(oio->oi_trunc == NULL);
2807                         oio->oi_trunc = osc_extent_get(ext);
2808                         OSC_EXTENT_DUMP(D_CACHE, ext,
2809                                         "trunc at "LPU64"\n", size);
2810                 }
2811                 osc_extent_put(env, ext);
2812         }
2813         if (waiting != NULL) {
2814                 int rc;
2815
2816                 /* ignore the result of osc_extent_wait the write initiator
2817                  * should take care of it. */
2818                 rc = osc_extent_wait(env, waiting, OES_INV);
2819                 if (rc < 0)
2820                         OSC_EXTENT_DUMP(D_CACHE, waiting, "error: %d.\n", rc);
2821
2822                 osc_extent_put(env, waiting);
2823                 waiting = NULL;
2824                 goto again;
2825         }
2826         RETURN(result);
2827 }
2828
2829 /**
2830  * Called after osc_io_setattr_end to add oio->oi_trunc back to cache.
2831  */
2832 void osc_cache_truncate_end(const struct lu_env *env, struct osc_io *oio,
2833                             struct osc_object *obj)
2834 {
2835         struct osc_extent *ext = oio->oi_trunc;
2836
2837         oio->oi_trunc = NULL;
2838         if (ext != NULL) {
2839                 bool unplug = false;
2840
2841                 EASSERT(ext->oe_nr_pages > 0, ext);
2842                 EASSERT(ext->oe_state == OES_TRUNC, ext);
2843                 EASSERT(!ext->oe_urgent, ext);
2844
2845                 OSC_EXTENT_DUMP(D_CACHE, ext, "trunc -> cache.\n");
2846                 osc_object_lock(obj);
2847                 osc_extent_state_set(ext, OES_CACHE);
2848                 if (ext->oe_fsync_wait && !ext->oe_urgent) {
2849                         ext->oe_urgent = 1;
2850                         cfs_list_move_tail(&ext->oe_link, &obj->oo_urgent_exts);
2851                         unplug = true;
2852                 }
2853                 osc_update_pending(obj, OBD_BRW_WRITE, ext->oe_nr_pages);
2854                 osc_object_unlock(obj);
2855                 osc_extent_put(env, ext);
2856
2857                 if (unplug)
2858                         osc_io_unplug_async(env, osc_cli(obj), obj);
2859         }
2860 }
2861
2862 /**
2863  * Wait for extents in a specific range to be written out.
2864  * The caller must have called osc_cache_writeback_range() to issue IO
2865  * otherwise it will take a long time for this function to finish.
2866  *
2867  * Caller must hold inode_mutex , or cancel exclusive dlm lock so that
2868  * nobody else can dirty this range of file while we're waiting for
2869  * extents to be written.
2870  */
2871 int osc_cache_wait_range(const struct lu_env *env, struct osc_object *obj,
2872                          pgoff_t start, pgoff_t end)
2873 {
2874         struct osc_extent *ext;
2875         pgoff_t index = start;
2876         int     result = 0;
2877         ENTRY;
2878
2879 again:
2880         osc_object_lock(obj);
2881         ext = osc_extent_search(obj, index);
2882         if (ext == NULL)
2883                 ext = first_extent(obj);
2884         else if (ext->oe_end < index)
2885                 ext = next_extent(ext);
2886         while (ext != NULL) {
2887                 int rc;
2888
2889                 if (ext->oe_start > end)
2890                         break;
2891
2892                 if (!ext->oe_fsync_wait) {
2893                         ext = next_extent(ext);
2894                         continue;
2895                 }
2896
2897                 EASSERT(ergo(ext->oe_state == OES_CACHE,
2898                              ext->oe_hp || ext->oe_urgent), ext);
2899                 EASSERT(ergo(ext->oe_state == OES_ACTIVE,
2900                              !ext->oe_hp && ext->oe_urgent), ext);
2901
2902                 index = ext->oe_end + 1;
2903                 osc_extent_get(ext);
2904                 osc_object_unlock(obj);
2905
2906                 rc = osc_extent_wait(env, ext, OES_INV);
2907                 if (result == 0)
2908                         result = rc;
2909                 osc_extent_put(env, ext);
2910                 goto again;
2911         }
2912         osc_object_unlock(obj);
2913
2914         OSC_IO_DEBUG(obj, "sync file range.\n");
2915         RETURN(result);
2916 }
2917
2918 /**
2919  * Called to write out a range of osc object.
2920  *
2921  * @hp     : should be set this is caused by lock cancel;
2922  * @discard: is set if dirty pages should be dropped - file will be deleted or
2923  *         truncated, this implies there is no partially discarding extents.
2924  *
2925  * Return how many pages will be issued, or error code if error occurred.
2926  */
2927 int osc_cache_writeback_range(const struct lu_env *env, struct osc_object *obj,
2928                               pgoff_t start, pgoff_t end, int hp, int discard)
2929 {
2930         struct osc_extent *ext;
2931         CFS_LIST_HEAD(discard_list);
2932         bool unplug = false;
2933         int result = 0;
2934         ENTRY;
2935
2936         osc_object_lock(obj);
2937         ext = osc_extent_search(obj, start);
2938         if (ext == NULL)
2939                 ext = first_extent(obj);
2940         else if (ext->oe_end < start)
2941                 ext = next_extent(ext);
2942         while (ext != NULL) {
2943                 if (ext->oe_start > end)
2944                         break;
2945
2946                 ext->oe_fsync_wait = 1;
2947                 switch (ext->oe_state) {
2948                 case OES_CACHE:
2949                         result += ext->oe_nr_pages;
2950                         if (!discard) {
2951                                 cfs_list_t *list = NULL;
2952                                 if (hp) {
2953                                         EASSERT(!ext->oe_hp, ext);
2954                                         ext->oe_hp = 1;
2955                                         list = &obj->oo_hp_exts;
2956                                 } else if (!ext->oe_urgent) {
2957                                         ext->oe_urgent = 1;
2958                                         list = &obj->oo_urgent_exts;
2959                                 }
2960                                 if (list != NULL)
2961                                         cfs_list_move_tail(&ext->oe_link, list);
2962                                 unplug = true;
2963                         } else {
2964                                 /* the only discarder is lock cancelling, so
2965                                  * [start, end] must contain this extent */
2966                                 EASSERT(ext->oe_start >= start &&
2967                                         ext->oe_max_end <= end, ext);
2968                                 osc_extent_state_set(ext, OES_LOCKING);
2969                                 ext->oe_owner = current;
2970                                 cfs_list_move_tail(&ext->oe_link,
2971                                                    &discard_list);
2972                                 osc_update_pending(obj, OBD_BRW_WRITE,
2973                                                    -ext->oe_nr_pages);
2974                         }
2975                         break;
2976                 case OES_ACTIVE:
2977                         /* It's pretty bad to wait for ACTIVE extents, because
2978                          * we don't know how long we will wait for it to be
2979                          * flushed since it may be blocked at awaiting more
2980                          * grants. We do this for the correctness of fsync. */
2981                         LASSERT(hp == 0 && discard == 0);
2982                         ext->oe_urgent = 1;
2983                         break;
2984                 case OES_TRUNC:
2985                         /* this extent is being truncated, can't do anything
2986                          * for it now. it will be set to urgent after truncate
2987                          * is finished in osc_cache_truncate_end(). */
2988                 default:
2989                         break;
2990                 }
2991                 ext = next_extent(ext);
2992         }
2993         osc_object_unlock(obj);
2994
2995         LASSERT(ergo(!discard, cfs_list_empty(&discard_list)));
2996         if (!cfs_list_empty(&discard_list)) {
2997                 struct osc_extent *tmp;
2998                 int rc;
2999
3000                 osc_list_maint(osc_cli(obj), obj);
3001                 cfs_list_for_each_entry_safe(ext, tmp, &discard_list, oe_link) {
3002                         cfs_list_del_init(&ext->oe_link);
3003                         EASSERT(ext->oe_state == OES_LOCKING, ext);
3004
3005                         /* Discard caching pages. We don't actually write this
3006                          * extent out but we complete it as if we did. */
3007                         rc = osc_extent_make_ready(env, ext);
3008                         if (unlikely(rc < 0)) {
3009                                 OSC_EXTENT_DUMP(D_ERROR, ext,
3010                                                 "make_ready returned %d\n", rc);
3011                                 if (result >= 0)
3012                                         result = rc;
3013                         }
3014
3015                         /* finish the extent as if the pages were sent */
3016                         osc_extent_finish(env, ext, 0, 0);
3017                 }
3018         }
3019
3020         if (unplug)
3021                 osc_io_unplug(env, osc_cli(obj), obj, PDL_POLICY_ROUND);
3022
3023         if (hp || discard) {
3024                 int rc;
3025                 rc = osc_cache_wait_range(env, obj, start, end);
3026                 if (result >= 0 && rc < 0)
3027                         result = rc;
3028         }
3029
3030         OSC_IO_DEBUG(obj, "pageout [%lu, %lu], %d.\n", start, end, result);
3031         RETURN(result);
3032 }
3033
3034 /** @} osc */