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