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