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