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