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