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