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