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