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