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