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