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