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