Whamcloud - gitweb
LU-4974 doc: comments to lod_qos.c
[fs/lustre-release.git] / lustre / lod / lod_qos.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,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License version 2 for more details.  A copy is
14  * included in the COPYING file that accompanied this code.
15
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright  2009 Sun Microsystems, Inc. All rights reserved
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2012, 2013, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lustre/lod/lod_qos.c
33  *
34  * Implementation of different allocation algorithm used
35  * to distribute objects and data among OSTs.
36  */
37
38 #define DEBUG_SUBSYSTEM S_LOV
39
40 #include <asm/div64.h>
41 #include <libcfs/libcfs.h>
42 #include <obd_class.h>
43 #include <lustre/lustre_idl.h>
44 #include "lod_internal.h"
45
46 /*
47  * force QoS policy (not RR) to be used for testing purposes
48  */
49 #define FORCE_QOS_
50
51 #define D_QOS   D_OTHER
52
53 #if 0
54 #define QOS_DEBUG(fmt, ...)     CDEBUG(D_OTHER, fmt, ## __VA_ARGS__)
55 #define QOS_CONSOLE(fmt, ...)   LCONSOLE(D_OTHER, fmt, ## __VA_ARGS__)
56 #else
57 #define QOS_DEBUG(fmt, ...)
58 #define QOS_CONSOLE(fmt, ...)
59 #endif
60
61 #define TGT_BAVAIL(i) (OST_TGT(lod,i)->ltd_statfs.os_bavail * \
62                        OST_TGT(lod,i)->ltd_statfs.os_bsize)
63
64 /**
65  * Add a new target to Quality of Service (QoS) target table.
66  *
67  * Add a new OST target to the structure representing an OSS. Resort the list
68  * of known OSSs by the number of OSTs attached to each OSS. The OSS list is
69  * protected internally and no external locking is required.
70  *
71  * \param[in] lod               LOD device
72  * \param[in] ost_desc          OST description
73  *
74  * \retval 0                    on success
75  * \retval -ENOMEM              on error
76  */
77 int qos_add_tgt(struct lod_device *lod, struct lod_tgt_desc *ost_desc)
78 {
79         struct lod_qos_oss *oss = NULL, *temposs;
80         struct obd_export  *exp = ost_desc->ltd_exp;
81         int                 rc = 0, found = 0;
82         struct list_head   *list;
83         ENTRY;
84
85         down_write(&lod->lod_qos.lq_rw_sem);
86         /*
87          * a bit hacky approach to learn NID of corresponding connection
88          * but there is no official API to access information like this
89          * with OSD API.
90          */
91         list_for_each_entry(oss, &lod->lod_qos.lq_oss_list, lqo_oss_list) {
92                 if (obd_uuid_equals(&oss->lqo_uuid,
93                                     &exp->exp_connection->c_remote_uuid)) {
94                         found++;
95                         break;
96                 }
97         }
98
99         if (!found) {
100                 OBD_ALLOC_PTR(oss);
101                 if (!oss)
102                         GOTO(out, rc = -ENOMEM);
103                 memcpy(&oss->lqo_uuid, &exp->exp_connection->c_remote_uuid,
104                        sizeof(oss->lqo_uuid));
105         } else {
106                 /* Assume we have to move this one */
107                 list_del(&oss->lqo_oss_list);
108         }
109
110         oss->lqo_ost_count++;
111         ost_desc->ltd_qos.ltq_oss = oss;
112
113         CDEBUG(D_QOS, "add tgt %s to OSS %s (%d OSTs)\n",
114                obd_uuid2str(&ost_desc->ltd_uuid), obd_uuid2str(&oss->lqo_uuid),
115                oss->lqo_ost_count);
116
117         /* Add sorted by # of OSTs.  Find the first entry that we're
118            bigger than... */
119         list = &lod->lod_qos.lq_oss_list;
120         list_for_each_entry(temposs, list, lqo_oss_list) {
121                 if (oss->lqo_ost_count > temposs->lqo_ost_count)
122                         break;
123         }
124         /* ...and add before it.  If we're the first or smallest, temposs
125            points to the list head, and we add to the end. */
126         list_add_tail(&oss->lqo_oss_list, &temposs->lqo_oss_list);
127
128         lod->lod_qos.lq_dirty = 1;
129         lod->lod_qos.lq_rr.lqr_dirty = 1;
130
131 out:
132         up_write(&lod->lod_qos.lq_rw_sem);
133         RETURN(rc);
134 }
135
136 /**
137  * Remove OST target from QoS table.
138  *
139  * Removes given OST target from QoS table and releases related OSS structure
140  * if no OSTs remain on the OSS.
141  *
142  * \param[in] lod               LOD device
143  * \param[in] ost_desc          OST description
144  *
145  * \retval 0                    on success
146  * \retval -ENOENT              if no OSS was found
147  */
148 int qos_del_tgt(struct lod_device *lod, struct lod_tgt_desc *ost_desc)
149 {
150         struct lod_qos_oss *oss;
151         int                 rc = 0;
152         ENTRY;
153
154         down_write(&lod->lod_qos.lq_rw_sem);
155         oss = ost_desc->ltd_qos.ltq_oss;
156         if (!oss)
157                 GOTO(out, rc = -ENOENT);
158
159         oss->lqo_ost_count--;
160         if (oss->lqo_ost_count == 0) {
161                 CDEBUG(D_QOS, "removing OSS %s\n",
162                        obd_uuid2str(&oss->lqo_uuid));
163                 list_del(&oss->lqo_oss_list);
164                 ost_desc->ltd_qos.ltq_oss = NULL;
165                 OBD_FREE_PTR(oss);
166         }
167
168         lod->lod_qos.lq_dirty = 1;
169         lod->lod_qos.lq_rr.lqr_dirty = 1;
170 out:
171         up_write(&lod->lod_qos.lq_rw_sem);
172         RETURN(rc);
173 }
174
175 /**
176  * Check whether the target is available for new OST objects.
177  *
178  * Request statfs data from the given target and verify it's active and not
179  * read-only. If so, then it can be used to place new OST objects. This
180  * function also maintains the number of active/inactive targets and sets
181  * dirty flags if those numbers change so others can run re-balance procedures.
182  * No external locking is required.
183  *
184  * \param[in] env       execution environment for this thread
185  * \param[in] d         LOD device
186  * \param[in] index     index of OST target to check
187  * \param[out] sfs      buffer for statfs data
188  *
189  * \retval 0            if the target is good
190  * \retval negative     negated errno on error
191
192  */
193 static int lod_statfs_and_check(const struct lu_env *env, struct lod_device *d,
194                                 int index, struct obd_statfs *sfs)
195 {
196         struct lod_tgt_desc *ost;
197         int                  rc;
198
199         LASSERT(d);
200         ost = OST_TGT(d,index);
201         LASSERT(ost);
202
203         rc = dt_statfs(env, ost->ltd_ost, sfs);
204         if (rc && rc != -ENOTCONN)
205                 CERROR("%s: statfs: rc = %d\n", lod2obd(d)->obd_name, rc);
206
207         /* If the OST is readonly then we can't allocate objects there */
208         if (sfs->os_state & OS_STATE_READONLY)
209                 rc = -EROFS;
210
211         /* check whether device has changed state (active, inactive) */
212         if (rc != 0 && ost->ltd_active) {
213                 /* turned inactive? */
214                 spin_lock(&d->lod_desc_lock);
215                 if (ost->ltd_active) {
216                         ost->ltd_active = 0;
217                         LASSERT(d->lod_desc.ld_active_tgt_count > 0);
218                         d->lod_desc.ld_active_tgt_count--;
219                         d->lod_qos.lq_dirty = 1;
220                         d->lod_qos.lq_rr.lqr_dirty = 1;
221                         CDEBUG(D_CONFIG, "%s: turns inactive\n",
222                                ost->ltd_exp->exp_obd->obd_name);
223                 }
224                 spin_unlock(&d->lod_desc_lock);
225         } else if (rc == 0 && ost->ltd_active == 0) {
226                 /* turned active? */
227                 LASSERTF(d->lod_desc.ld_active_tgt_count < d->lod_ostnr,
228                          "active tgt count %d, ost nr %d\n",
229                          d->lod_desc.ld_active_tgt_count, d->lod_ostnr);
230                 spin_lock(&d->lod_desc_lock);
231                 if (ost->ltd_active == 0) {
232                         ost->ltd_active = 1;
233                         d->lod_desc.ld_active_tgt_count++;
234                         d->lod_qos.lq_dirty = 1;
235                         d->lod_qos.lq_rr.lqr_dirty = 1;
236                         CDEBUG(D_CONFIG, "%s: turns active\n",
237                                ost->ltd_exp->exp_obd->obd_name);
238                 }
239                 spin_unlock(&d->lod_desc_lock);
240         }
241
242         RETURN(rc);
243 }
244
245 /**
246  * Maintain per-target statfs data.
247  *
248  * The function refreshes statfs data for all the targets every N seconds.
249  * The actual N is controlled via procfs and set to LOV_DESC_QOS_MAXAGE_DEFAULT
250  * initially.
251  *
252  * \param[in] env       execution environment for this thread
253  * \param[in] lod       LOD device
254  */
255 static void lod_qos_statfs_update(const struct lu_env *env,
256                                   struct lod_device *lod)
257 {
258         struct obd_device *obd = lod2obd(lod);
259         struct ost_pool   *osts = &(lod->lod_pool_info);
260         unsigned int       i;
261         int                idx, rc = 0;
262         __u64              max_age, avail;
263         ENTRY;
264
265         max_age = cfs_time_shift_64(-2 * lod->lod_desc.ld_qos_maxage);
266
267         if (cfs_time_beforeq_64(max_age, obd->obd_osfs_age))
268                 /* statfs data are quite recent, don't need to refresh it */
269                 RETURN_EXIT;
270
271         down_write(&lod->lod_qos.lq_rw_sem);
272         if (cfs_time_beforeq_64(max_age, obd->obd_osfs_age))
273                 GOTO(out, rc = 0);
274
275         for (i = 0; i < osts->op_count; i++) {
276                 idx = osts->op_array[i];
277                 avail = OST_TGT(lod,idx)->ltd_statfs.os_bavail;
278                 rc = lod_statfs_and_check(env, lod, idx,
279                                           &OST_TGT(lod,idx)->ltd_statfs);
280                 if (rc)
281                         break;
282                 if (OST_TGT(lod,idx)->ltd_statfs.os_bavail != avail)
283                         /* recalculate weigths */
284                         lod->lod_qos.lq_dirty = 1;
285         }
286         obd->obd_osfs_age = cfs_time_current_64();
287
288 out:
289         up_write(&lod->lod_qos.lq_rw_sem);
290         EXIT;
291 }
292
293 /**
294  * Calculate per-OST and per-OSS penalties
295  *
296  * Re-calculate penalties when the configuration changes, active targets
297  * change and after statfs refresh (all these are reflected by lq_dirty flag).
298  * On every OST and OSS: decay the penalty by half for every 8x the update
299  * interval that the device has been idle. That gives lots of time for the
300  * statfs information to be updated (which the penalty is only a proxy for),
301  * and avoids penalizing OSS/OSTs under light load.
302  * See lod_qos_calc_weight() for how penalties are factored into the weight.
303  *
304  * \param[in] lod       LOD device
305  *
306  * \retval 0            on success
307  * \retval -EAGAIN      the number of OSTs isn't enough
308  */
309 static int lod_qos_calc_ppo(struct lod_device *lod)
310 {
311         struct lod_qos_oss *oss;
312         __u64               ba_max, ba_min, temp;
313         __u32               num_active;
314         unsigned int        i;
315         int                 rc, prio_wide;
316         time_t              now, age;
317         ENTRY;
318
319         if (!lod->lod_qos.lq_dirty)
320                 GOTO(out, rc = 0);
321
322         num_active = lod->lod_desc.ld_active_tgt_count - 1;
323         if (num_active < 1)
324                 GOTO(out, rc = -EAGAIN);
325
326         /* find bavail on each OSS */
327         list_for_each_entry(oss, &lod->lod_qos.lq_oss_list, lqo_oss_list)
328                             oss->lqo_bavail = 0;
329         lod->lod_qos.lq_active_oss_count = 0;
330
331         /*
332          * How badly user wants to select OSTs "widely" (not recently chosen
333          * and not on recent OSS's).  As opposed to "freely" (free space
334          * avail.) 0-256
335          */
336         prio_wide = 256 - lod->lod_qos.lq_prio_free;
337
338         ba_min = (__u64)(-1);
339         ba_max = 0;
340         now = cfs_time_current_sec();
341         /* Calculate OST penalty per object
342          * (lod ref taken in lod_qos_prep_create()) */
343         cfs_foreach_bit(lod->lod_ost_bitmap, i) {
344                 LASSERT(OST_TGT(lod,i));
345                 temp = TGT_BAVAIL(i);
346                 if (!temp)
347                         continue;
348                 ba_min = min(temp, ba_min);
349                 ba_max = max(temp, ba_max);
350
351                 /* Count the number of usable OSS's */
352                 if (OST_TGT(lod,i)->ltd_qos.ltq_oss->lqo_bavail == 0)
353                         lod->lod_qos.lq_active_oss_count++;
354                 OST_TGT(lod,i)->ltd_qos.ltq_oss->lqo_bavail += temp;
355
356                 /* per-OST penalty is prio * TGT_bavail / (num_ost - 1) / 2 */
357                 temp >>= 1;
358                 do_div(temp, num_active);
359                 OST_TGT(lod,i)->ltd_qos.ltq_penalty_per_obj =
360                         (temp * prio_wide) >> 8;
361
362                 age = (now - OST_TGT(lod,i)->ltd_qos.ltq_used) >> 3;
363                 if (lod->lod_qos.lq_reset ||
364                     age > 32 * lod->lod_desc.ld_qos_maxage)
365                         OST_TGT(lod,i)->ltd_qos.ltq_penalty = 0;
366                 else if (age > lod->lod_desc.ld_qos_maxage)
367                         /* Decay OST penalty. */
368                         OST_TGT(lod,i)->ltd_qos.ltq_penalty >>=
369                                 (age / lod->lod_desc.ld_qos_maxage);
370         }
371
372         num_active = lod->lod_qos.lq_active_oss_count - 1;
373         if (num_active < 1) {
374                 /* If there's only 1 OSS, we can't penalize it, so instead
375                    we have to double the OST penalty */
376                 num_active = 1;
377                 cfs_foreach_bit(lod->lod_ost_bitmap, i)
378                         OST_TGT(lod,i)->ltd_qos.ltq_penalty_per_obj <<= 1;
379         }
380
381         /* Per-OSS penalty is prio * oss_avail / oss_osts / (num_oss - 1) / 2 */
382         list_for_each_entry(oss, &lod->lod_qos.lq_oss_list, lqo_oss_list) {
383                 temp = oss->lqo_bavail >> 1;
384                 do_div(temp, oss->lqo_ost_count * num_active);
385                 oss->lqo_penalty_per_obj = (temp * prio_wide) >> 8;
386
387                 age = (now - oss->lqo_used) >> 3;
388                 if (lod->lod_qos.lq_reset ||
389                     age > 32 * lod->lod_desc.ld_qos_maxage)
390                         oss->lqo_penalty = 0;
391                 else if (age > lod->lod_desc.ld_qos_maxage)
392                         /* Decay OSS penalty. */
393                         oss->lqo_penalty >>= age / lod->lod_desc.ld_qos_maxage;
394         }
395
396         lod->lod_qos.lq_dirty = 0;
397         lod->lod_qos.lq_reset = 0;
398
399         /* If each ost has almost same free space,
400          * do rr allocation for better creation performance */
401         lod->lod_qos.lq_same_space = 0;
402         if ((ba_max * (256 - lod->lod_qos.lq_threshold_rr)) >> 8 < ba_min) {
403                 lod->lod_qos.lq_same_space = 1;
404                 /* Reset weights for the next time we enter qos mode */
405                 lod->lod_qos.lq_reset = 1;
406         }
407         rc = 0;
408
409 out:
410 #ifndef FORCE_QOS
411         if (!rc && lod->lod_qos.lq_same_space)
412                 RETURN(-EAGAIN);
413 #endif
414         RETURN(rc);
415 }
416
417 /**
418  * Calculate weight for a given OST target.
419  *
420  * The final OST weight is the number of bytes available minus the OST and
421  * OSS penalties.  See lod_qos_calc_ppo() for how penalties are calculated.
422  *
423  * \param[in] lod       LOD device, where OST targets are listed
424  * \param[in] i         OST target index
425  *
426  * \retval              0
427  */
428 static int lod_qos_calc_weight(struct lod_device *lod, int i)
429 {
430         __u64 temp, temp2;
431
432         temp = TGT_BAVAIL(i);
433         temp2 = OST_TGT(lod,i)->ltd_qos.ltq_penalty +
434                 OST_TGT(lod,i)->ltd_qos.ltq_oss->lqo_penalty;
435         if (temp < temp2)
436                 OST_TGT(lod,i)->ltd_qos.ltq_weight = 0;
437         else
438                 OST_TGT(lod,i)->ltd_qos.ltq_weight = temp - temp2;
439         return 0;
440 }
441
442 /**
443  * Re-calculate weights.
444  *
445  * The function is called when some OST target was used for a new object. In
446  * this case we should re-calculate all the weights to keep new allocations
447  * balanced well.
448  *
449  * \param[in] lod       LOD device
450  * \param[in] osts      OST pool where a new object was placed
451  * \param[in] index     OST target where a new object was placed
452  * \param[out] total_wt new total weight for the pool
453  *
454  * \retval              0
455  */
456 static int lod_qos_used(struct lod_device *lod, struct ost_pool *osts,
457                         __u32 index, __u64 *total_wt)
458 {
459         struct lod_tgt_desc *ost;
460         struct lod_qos_oss  *oss;
461         unsigned int j;
462         ENTRY;
463
464         ost = OST_TGT(lod,index);
465         LASSERT(ost);
466
467         /* Don't allocate on this devuce anymore, until the next alloc_qos */
468         ost->ltd_qos.ltq_usable = 0;
469
470         oss = ost->ltd_qos.ltq_oss;
471
472         /* Decay old penalty by half (we're adding max penalty, and don't
473            want it to run away.) */
474         ost->ltd_qos.ltq_penalty >>= 1;
475         oss->lqo_penalty >>= 1;
476
477         /* mark the OSS and OST as recently used */
478         ost->ltd_qos.ltq_used = oss->lqo_used = cfs_time_current_sec();
479
480         /* Set max penalties for this OST and OSS */
481         ost->ltd_qos.ltq_penalty +=
482                 ost->ltd_qos.ltq_penalty_per_obj * lod->lod_ostnr;
483         oss->lqo_penalty += oss->lqo_penalty_per_obj *
484                 lod->lod_qos.lq_active_oss_count;
485
486         /* Decrease all OSS penalties */
487         list_for_each_entry(oss, &lod->lod_qos.lq_oss_list, lqo_oss_list) {
488                 if (oss->lqo_penalty < oss->lqo_penalty_per_obj)
489                         oss->lqo_penalty = 0;
490                 else
491                         oss->lqo_penalty -= oss->lqo_penalty_per_obj;
492         }
493
494         *total_wt = 0;
495         /* Decrease all OST penalties */
496         for (j = 0; j < osts->op_count; j++) {
497                 int i;
498
499                 i = osts->op_array[j];
500                 if (!cfs_bitmap_check(lod->lod_ost_bitmap, i))
501                         continue;
502
503                 ost = OST_TGT(lod,i);
504                 LASSERT(ost);
505
506                 if (ost->ltd_qos.ltq_penalty <
507                                 ost->ltd_qos.ltq_penalty_per_obj)
508                         ost->ltd_qos.ltq_penalty = 0;
509                 else
510                         ost->ltd_qos.ltq_penalty -=
511                                 ost->ltd_qos.ltq_penalty_per_obj;
512
513                 lod_qos_calc_weight(lod, i);
514
515                 /* Recalc the total weight of usable osts */
516                 if (ost->ltd_qos.ltq_usable)
517                         *total_wt += ost->ltd_qos.ltq_weight;
518
519                 QOS_DEBUG("recalc tgt %d usable=%d avail="LPU64
520                           " ostppo="LPU64" ostp="LPU64" ossppo="LPU64
521                           " ossp="LPU64" wt="LPU64"\n",
522                           i, ost->ltd_qos.ltq_usable, TGT_BAVAIL(i) >> 10,
523                           ost->ltd_qos.ltq_penalty_per_obj >> 10,
524                           ost->ltd_qos.ltq_penalty >> 10,
525                           ost->ltd_qos.ltq_oss->lqo_penalty_per_obj >> 10,
526                           ost->ltd_qos.ltq_oss->lqo_penalty >> 10,
527                           ost->ltd_qos.ltq_weight >> 10);
528         }
529
530         RETURN(0);
531 }
532
533 #define LOV_QOS_EMPTY ((__u32)-1)
534
535 /**
536  * Calculate optimal round-robin order with regard to OSSes.
537  *
538  * Place all the OSTs from pool \a src_pool in a special array to be used for
539  * round-robin (RR) stripe allocation.  The placement algorithm interleaves
540  * OSTs from the different OSSs so that RR allocation can balance OSSs evenly.
541  * Resorts the targets when the number of active targets changes (because of
542  * a new target or activation/deactivation).
543  *
544  * \param[in] lod       LOD device
545  * \param[in] src_pool  OST pool
546  * \param[in] lqr       round-robin list
547  *
548  * \retval 0            on success
549  * \retval -ENOMEM      fails to allocate the array
550  */
551 static int lod_qos_calc_rr(struct lod_device *lod, struct ost_pool *src_pool,
552                            struct lod_qos_rr *lqr)
553 {
554         struct lod_qos_oss  *oss;
555         struct lod_tgt_desc *ost;
556         unsigned placed, real_count;
557         unsigned int i;
558         int rc;
559         ENTRY;
560
561         if (!lqr->lqr_dirty) {
562                 LASSERT(lqr->lqr_pool.op_size);
563                 RETURN(0);
564         }
565
566         /* Do actual allocation. */
567         down_write(&lod->lod_qos.lq_rw_sem);
568
569         /*
570          * Check again. While we were sleeping on @lq_rw_sem something could
571          * change.
572          */
573         if (!lqr->lqr_dirty) {
574                 LASSERT(lqr->lqr_pool.op_size);
575                 up_write(&lod->lod_qos.lq_rw_sem);
576                 RETURN(0);
577         }
578
579         real_count = src_pool->op_count;
580
581         /* Zero the pool array */
582         /* alloc_rr is holding a read lock on the pool, so nobody is adding/
583            deleting from the pool. The lq_rw_sem insures that nobody else
584            is reading. */
585         lqr->lqr_pool.op_count = real_count;
586         rc = lod_ost_pool_extend(&lqr->lqr_pool, real_count);
587         if (rc) {
588                 up_write(&lod->lod_qos.lq_rw_sem);
589                 RETURN(rc);
590         }
591         for (i = 0; i < lqr->lqr_pool.op_count; i++)
592                 lqr->lqr_pool.op_array[i] = LOV_QOS_EMPTY;
593
594         /* Place all the OSTs from 1 OSS at the same time. */
595         placed = 0;
596         list_for_each_entry(oss, &lod->lod_qos.lq_oss_list, lqo_oss_list) {
597                 int j = 0;
598
599                 for (i = 0; i < lqr->lqr_pool.op_count; i++) {
600                         int next;
601
602                         if (!cfs_bitmap_check(lod->lod_ost_bitmap,
603                                                 src_pool->op_array[i]))
604                                 continue;
605
606                         ost = OST_TGT(lod,src_pool->op_array[i]);
607                         LASSERT(ost && ost->ltd_ost);
608                         if (ost->ltd_qos.ltq_oss != oss)
609                                 continue;
610
611                         /* Evenly space these OSTs across arrayspace */
612                         next = j * lqr->lqr_pool.op_count / oss->lqo_ost_count;
613                         while (lqr->lqr_pool.op_array[next] != LOV_QOS_EMPTY)
614                                 next = (next + 1) % lqr->lqr_pool.op_count;
615
616                         lqr->lqr_pool.op_array[next] = src_pool->op_array[i];
617                         j++;
618                         placed++;
619                 }
620         }
621
622         lqr->lqr_dirty = 0;
623         up_write(&lod->lod_qos.lq_rw_sem);
624
625         if (placed != real_count) {
626                 /* This should never happen */
627                 LCONSOLE_ERROR_MSG(0x14e, "Failed to place all OSTs in the "
628                                    "round-robin list (%d of %d).\n",
629                                    placed, real_count);
630                 for (i = 0; i < lqr->lqr_pool.op_count; i++) {
631                         LCONSOLE(D_WARNING, "rr #%d ost idx=%d\n", i,
632                                  lqr->lqr_pool.op_array[i]);
633                 }
634                 lqr->lqr_dirty = 1;
635                 RETURN(-EAGAIN);
636         }
637
638 #if 0
639         for (i = 0; i < lqr->lqr_pool.op_count; i++)
640                 QOS_CONSOLE("rr #%d ost idx=%d\n", i, lqr->lqr_pool.op_array[i]);
641 #endif
642
643         RETURN(0);
644 }
645
646 /**
647  * Instantiate and declare creation of a new object.
648  *
649  * The function instantiates LU representation for a new object on the
650  * specified device. Also it declares an intention to create that
651  * object on the storage target.
652  *
653  * Note lu_object_anon() is used which is a trick with regard to LU/OSD
654  * infrastructure - in the existing precreation framework we can't assign FID
655  * at this moment, we do this later once a transaction is started. So the
656  * special method instantiates FID-less object in the cache and later it
657  * will get a FID and proper placement in LU cache.
658  *
659  * \param[in] env       execution environment for this thread
660  * \param[in] d         LOD device
661  * \param[in] ost_idx   OST target index where the object is being created
662  * \param[in] th        transaction handle
663  *
664  * \retval              object ptr on success, ERR_PTR() otherwise
665  */
666 static struct dt_object *lod_qos_declare_object_on(const struct lu_env *env,
667                                                    struct lod_device *d,
668                                                    __u32 ost_idx,
669                                                    struct thandle *th)
670 {
671         struct lod_tgt_desc *ost;
672         struct lu_object *o, *n;
673         struct lu_device *nd;
674         struct dt_object *dt;
675         int               rc;
676         ENTRY;
677
678         LASSERT(d);
679         LASSERT(ost_idx < d->lod_osts_size);
680         ost = OST_TGT(d,ost_idx);
681         LASSERT(ost);
682         LASSERT(ost->ltd_ost);
683
684         nd = &ost->ltd_ost->dd_lu_dev;
685
686         /*
687          * allocate anonymous object with zero fid, real fid
688          * will be assigned by OSP within transaction
689          * XXX: to be fixed with fully-functional OST fids
690          */
691         o = lu_object_anon(env, nd, NULL);
692         if (IS_ERR(o))
693                 GOTO(out, dt = ERR_PTR(PTR_ERR(o)));
694
695         n = lu_object_locate(o->lo_header, nd->ld_type);
696         if (unlikely(n == NULL)) {
697                 CERROR("can't find slice\n");
698                 lu_object_put(env, o);
699                 GOTO(out, dt = ERR_PTR(-EINVAL));
700         }
701
702         dt = container_of(n, struct dt_object, do_lu);
703
704         rc = dt_declare_create(env, dt, NULL, NULL, NULL, th);
705         if (rc) {
706                 CDEBUG(D_OTHER, "can't declare creation on #%u: %d\n",
707                        ost_idx, rc);
708                 lu_object_put(env, o);
709                 dt = ERR_PTR(rc);
710         }
711
712 out:
713         RETURN(dt);
714 }
715
716 /**
717  * Calculate a minimum acceptable stripe count.
718  *
719  * Return an acceptable stripe count depending on flag LOV_USES_DEFAULT_STRIPE:
720  * all stripes or 3/4 of stripes.
721  *
722  * \param[in] stripe_cnt        number of stripes requested
723  * \param[in] flags             0 or LOV_USES_DEFAULT_STRIPE
724  *
725  * \retval                      acceptable stripecount
726  */
727 static int min_stripe_count(__u32 stripe_cnt, int flags)
728 {
729         return (flags & LOV_USES_DEFAULT_STRIPE ?
730                         stripe_cnt - (stripe_cnt / 4) : stripe_cnt);
731 }
732
733 #define LOV_CREATE_RESEED_MULT 30
734 #define LOV_CREATE_RESEED_MIN  2000
735
736 /**
737  * Check if an OST is full.
738  *
739  * Check whether an OST should be considered full based
740  * on the given statfs data.
741  *
742  * \param[in] msfs      statfs data
743  *
744  * \retval false        not full
745  * \retval true         full
746  */
747 static int inline lod_qos_dev_is_full(struct obd_statfs *msfs)
748 {
749         __u64 used;
750         int   bs = msfs->os_bsize;
751
752         LASSERT(((bs - 1) & bs) == 0);
753
754         /* the minimum of 0.1% used blocks and 1GB bytes. */
755         used = min_t(__u64, (msfs->os_blocks - msfs->os_bfree) >> 10,
756                         1 << (31 - ffs(bs)));
757         return (msfs->os_bavail < used);
758 }
759
760 /**
761  * Initialize temporary OST-in-use array.
762  *
763  * Allocate or extend the array used to mark targets already assigned to a new
764  * striping so they are not used more than once.
765  *
766  * \param[in] env       execution environment for this thread
767  * \param[in] stripes   number of items needed in the array
768  *
769  * \retval 0            on success
770  * \retval -ENOMEM      on error
771  */
772 static inline int lod_qos_ost_in_use_clear(const struct lu_env *env,
773                                            __u32 stripes)
774 {
775         struct lod_thread_info *info = lod_env_info(env);
776
777         if (info->lti_ea_store_size < sizeof(int) * stripes)
778                 lod_ea_store_resize(info, stripes * sizeof(int));
779         if (info->lti_ea_store_size < sizeof(int) * stripes) {
780                 CERROR("can't allocate memory for ost-in-use array\n");
781                 return -ENOMEM;
782         }
783         memset(info->lti_ea_store, -1, sizeof(int) * stripes);
784         return 0;
785 }
786
787 /**
788  * Remember a target in the array of used targets.
789  *
790  * Mark the given target as used for a new striping being created. The status
791  * of an OST in a striping can be checked with lod_qos_is_ost_used().
792  *
793  * \param[in] env       execution environment for this thread
794  * \param[in] idx       index in the array
795  * \param[in] ost       OST target index to mark as used
796  */
797 static inline void lod_qos_ost_in_use(const struct lu_env *env,
798                                       int idx, int ost)
799 {
800         struct lod_thread_info *info = lod_env_info(env);
801         int *osts = info->lti_ea_store;
802
803         LASSERT(info->lti_ea_store_size >= idx * sizeof(int));
804         osts[idx] = ost;
805 }
806
807 /**
808  * Check is OST used in a striping.
809  *
810  * Checks whether OST with the given index is marked as used in the temporary
811  * array (see lod_qos_ost_in_use()).
812  *
813  * \param[in] env       execution environment for this thread
814  * \param[in] ost       OST target index to check
815  * \param[in] stripes   the number of items used in the array already
816  *
817  * \retval 0            not used
818  * \retval 1            used
819  */
820 static int lod_qos_is_ost_used(const struct lu_env *env, int ost, __u32 stripes)
821 {
822         struct lod_thread_info *info = lod_env_info(env);
823         int *osts = info->lti_ea_store;
824         __u32 j;
825
826         for (j = 0; j < stripes; j++) {
827                 if (osts[j] == ost)
828                         return 1;
829         }
830         return 0;
831 }
832
833 /**
834  * Allocate a striping using round-robin algorigthm.
835  *
836  * Allocates a new striping using round-robin algorithm. The function refreshes
837  * all the internal structures (statfs cache, array of available OSTs sorted
838  * with regard to OSS, etc). The number of stripes required is taken from the
839  * object (must be prepared by the caller), but can change if the flag
840  * LOV_USES_DEFAULT_STRIPE is supplied. The caller should ensure nobody else
841  * is trying to create a striping on the object in parallel. All the internal
842  * structures (like pools, etc) are protected and no additional locking is
843  * required. The function succeeds even if a single stripe is allocated. To save
844  * time we give priority to targets which already have objects precreated.
845  * Full OSTs are skipped (see lod_qos_dev_is_full() for the details).
846  *
847  * \param[in] env       execution environment for this thread
848  * \param[in] lo        LOD object
849  * \param[out] stripe   striping created
850  * \param[in] flags     allocation flags (0 or LOV_USES_DEFAULT_STRIPE)
851  * \param[in] th        transaction handle
852  *
853  * \retval 0            on success
854  * \retval -ENOSPC      if not enough OSTs are found
855  * \retval negative     negated errno for other failures
856  */
857 static int lod_alloc_rr(const struct lu_env *env, struct lod_object *lo,
858                         struct dt_object **stripe, int flags,
859                         struct thandle *th)
860 {
861         struct lod_device *m = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
862         struct obd_statfs *sfs = &lod_env_info(env)->lti_osfs;
863         struct pool_desc  *pool = NULL;
864         struct ost_pool   *osts;
865         struct lod_qos_rr *lqr;
866         struct dt_object  *o;
867         unsigned int       i, array_idx;
868         int                rc;
869         __u32              ost_start_idx_temp;
870         int                speed = 0;
871         __u32              stripe_idx = 0;
872         __u32              stripe_cnt = lo->ldo_stripenr;
873         __u32              stripe_cnt_min = min_stripe_count(stripe_cnt, flags);
874         __u32              ost_idx;
875         ENTRY;
876
877         if (lo->ldo_pool)
878                 pool = lod_find_pool(m, lo->ldo_pool);
879
880         if (pool != NULL) {
881                 down_read(&pool_tgt_rw_sem(pool));
882                 osts = &(pool->pool_obds);
883                 lqr = &(pool->pool_rr);
884         } else {
885                 osts = &(m->lod_pool_info);
886                 lqr = &(m->lod_qos.lq_rr);
887         }
888
889         rc = lod_qos_calc_rr(m, osts, lqr);
890         if (rc)
891                 GOTO(out, rc);
892
893         rc = lod_qos_ost_in_use_clear(env, lo->ldo_stripenr);
894         if (rc)
895                 GOTO(out, rc);
896
897         if (--lqr->lqr_start_count <= 0) {
898                 lqr->lqr_start_idx = cfs_rand() % osts->op_count;
899                 lqr->lqr_start_count =
900                         (LOV_CREATE_RESEED_MIN / max(osts->op_count, 1U) +
901                          LOV_CREATE_RESEED_MULT) * max(osts->op_count, 1U);
902         } else if (stripe_cnt_min >= osts->op_count ||
903                         lqr->lqr_start_idx > osts->op_count) {
904                 /* If we have allocated from all of the OSTs, slowly
905                  * precess the next start if the OST/stripe count isn't
906                  * already doing this for us. */
907                 lqr->lqr_start_idx %= osts->op_count;
908                 if (stripe_cnt > 1 && (osts->op_count % stripe_cnt) != 1)
909                         ++lqr->lqr_offset_idx;
910         }
911         down_read(&m->lod_qos.lq_rw_sem);
912         ost_start_idx_temp = lqr->lqr_start_idx;
913
914 repeat_find:
915         array_idx = (lqr->lqr_start_idx + lqr->lqr_offset_idx) %
916                         osts->op_count;
917
918         QOS_DEBUG("pool '%s' want %d startidx %d startcnt %d offset %d "
919                   "active %d count %d arrayidx %d\n",
920                   lo->ldo_pool ? lo->ldo_pool : "",
921                   stripe_cnt, lqr->lqr_start_idx, lqr->lqr_start_count,
922                   lqr->lqr_offset_idx, osts->op_count, osts->op_count,
923                   array_idx);
924
925         for (i = 0; i < osts->op_count && stripe_idx < lo->ldo_stripenr;
926              i++, array_idx = (array_idx + 1) % osts->op_count) {
927                 ++lqr->lqr_start_idx;
928                 ost_idx = lqr->lqr_pool.op_array[array_idx];
929
930                 QOS_DEBUG("#%d strt %d act %d strp %d ary %d idx %d\n",
931                           i, lqr->lqr_start_idx, /* XXX: active*/ 0,
932                           stripe_idx, array_idx, ost_idx);
933
934                 if ((ost_idx == LOV_QOS_EMPTY) ||
935                     !cfs_bitmap_check(m->lod_ost_bitmap, ost_idx))
936                         continue;
937
938                 /* Fail Check before osc_precreate() is called
939                    so we can only 'fail' single OSC. */
940                 if (OBD_FAIL_CHECK(OBD_FAIL_MDS_OSC_PRECREATE) && ost_idx == 0)
941                         continue;
942
943                 rc = lod_statfs_and_check(env, m, ost_idx, sfs);
944                 if (rc) {
945                         /* this OSP doesn't feel well */
946                         continue;
947                 }
948
949                 /*
950                  * skip full devices
951                  */
952                 if (lod_qos_dev_is_full(sfs)) {
953                         QOS_DEBUG("#%d is full\n", ost_idx);
954                         continue;
955                 }
956
957                 /*
958                  * We expect number of precreated objects in f_ffree at
959                  * the first iteration, skip OSPs with no objects ready
960                  */
961                 if (sfs->os_fprecreated == 0 && speed == 0) {
962                         QOS_DEBUG("#%d: precreation is empty\n", ost_idx);
963                         continue;
964                 }
965
966                 /*
967                  * try to use another OSP if this one is degraded
968                  */
969                 if (sfs->os_state & OS_STATE_DEGRADED && speed < 2) {
970                         QOS_DEBUG("#%d: degraded\n", ost_idx);
971                         continue;
972                 }
973
974                 /*
975                  * do not put >1 objects on a single OST
976                  */
977                 if (speed && lod_qos_is_ost_used(env, ost_idx, stripe_idx))
978                         continue;
979
980                 o = lod_qos_declare_object_on(env, m, ost_idx, th);
981                 if (IS_ERR(o)) {
982                         CDEBUG(D_OTHER, "can't declare new object on #%u: %d\n",
983                                ost_idx, (int) PTR_ERR(o));
984                         rc = PTR_ERR(o);
985                         continue;
986                 }
987
988                 /*
989                  * We've successfuly declared (reserved) an object
990                  */
991                 lod_qos_ost_in_use(env, stripe_idx, ost_idx);
992                 stripe[stripe_idx] = o;
993                 stripe_idx++;
994
995         }
996         if ((speed < 2) && (stripe_idx < stripe_cnt_min)) {
997                 /* Try again, allowing slower OSCs */
998                 speed++;
999                 lqr->lqr_start_idx = ost_start_idx_temp;
1000                 goto repeat_find;
1001         }
1002
1003         up_read(&m->lod_qos.lq_rw_sem);
1004
1005         if (stripe_idx) {
1006                 lo->ldo_stripenr = stripe_idx;
1007                 /* at least one stripe is allocated */
1008                 rc = 0;
1009         } else {
1010                 /* nobody provided us with a single object */
1011                 rc = -ENOSPC;
1012         }
1013
1014 out:
1015         if (pool != NULL) {
1016                 up_read(&pool_tgt_rw_sem(pool));
1017                 /* put back ref got by lod_find_pool() */
1018                 lod_pool_putref(pool);
1019         }
1020
1021         RETURN(rc);
1022 }
1023
1024 /**
1025  * Allocate a striping on a predefined set of OSTs.
1026  *
1027  * Allocates new striping starting from OST provided lo->ldo_def_stripe_offset.
1028  * Full OSTs are not considered. The exact order of OSTs is not important and
1029  * varies depending on OST status. The allocation procedure prefers the targets
1030  * with precreated objects ready. The number of stripes needed and stripe
1031  * offset are taken from the object. If that number can not be met, then the
1032  * function returns a failure and then it's the caller's responsibility to
1033  * release the stripes allocated. All the internal structures are protected,
1034  * but no concurrent allocation is allowed on the same objects.
1035  *
1036  * \param[in] env       execution environment for this thread
1037  * \param[in] lo        LOD object
1038  * \param[out] stripe   striping created
1039  * \param[in] flags     not used
1040  * \param[in] th        transaction handle
1041  *
1042  * \retval 0            on success
1043  * \retval -E2BIG       if no enough OSTs are found
1044  * \retval -EINVAL      requested offset is invalid
1045  * \retval negative     negated errno on error
1046  */
1047 static int lod_alloc_specific(const struct lu_env *env, struct lod_object *lo,
1048                               struct dt_object **stripe, int flags,
1049                               struct thandle *th)
1050 {
1051         struct lod_device *m = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1052         struct obd_statfs *sfs = &lod_env_info(env)->lti_osfs;
1053         struct dt_object  *o;
1054         __u32              ost_idx;
1055         unsigned int       i, array_idx, ost_count;
1056         int                rc, stripe_num = 0;
1057         int                speed = 0;
1058         struct pool_desc  *pool = NULL;
1059         struct ost_pool   *osts;
1060         ENTRY;
1061
1062         rc = lod_qos_ost_in_use_clear(env, lo->ldo_stripenr);
1063         if (rc)
1064                 GOTO(out, rc);
1065
1066         if (lo->ldo_pool)
1067                 pool = lod_find_pool(m, lo->ldo_pool);
1068
1069         if (pool != NULL) {
1070                 down_read(&pool_tgt_rw_sem(pool));
1071                 osts = &(pool->pool_obds);
1072         } else {
1073                 osts = &(m->lod_pool_info);
1074         }
1075
1076         ost_count = osts->op_count;
1077
1078 repeat_find:
1079         /* search loi_ost_idx in ost array */
1080         array_idx = 0;
1081         for (i = 0; i < ost_count; i++) {
1082                 if (osts->op_array[i] == lo->ldo_def_stripe_offset) {
1083                         array_idx = i;
1084                         break;
1085                 }
1086         }
1087         if (i == ost_count) {
1088                 CERROR("Start index %d not found in pool '%s'\n",
1089                        lo->ldo_def_stripe_offset,
1090                        lo->ldo_pool ? lo->ldo_pool : "");
1091                 GOTO(out, rc = -EINVAL);
1092         }
1093
1094         for (i = 0; i < ost_count;
1095                         i++, array_idx = (array_idx + 1) % ost_count) {
1096                 ost_idx = osts->op_array[array_idx];
1097
1098                 if (!cfs_bitmap_check(m->lod_ost_bitmap, ost_idx))
1099                         continue;
1100
1101                 /* Fail Check before osc_precreate() is called
1102                    so we can only 'fail' single OSC. */
1103                 if (OBD_FAIL_CHECK(OBD_FAIL_MDS_OSC_PRECREATE) && ost_idx == 0)
1104                         continue;
1105
1106                 /*
1107                  * do not put >1 objects on a single OST
1108                  */
1109                 if (lod_qos_is_ost_used(env, ost_idx, stripe_num))
1110                         continue;
1111
1112                 /* Drop slow OSCs if we can, but not for requested start idx.
1113                  *
1114                  * This means "if OSC is slow and it is not the requested
1115                  * start OST, then it can be skipped, otherwise skip it only
1116                  * if it is inactive/recovering/out-of-space." */
1117
1118                 rc = lod_statfs_and_check(env, m, ost_idx, sfs);
1119                 if (rc) {
1120                         /* this OSP doesn't feel well */
1121                         continue;
1122                 }
1123
1124                 /*
1125                  * We expect number of precreated objects in f_ffree at
1126                  * the first iteration, skip OSPs with no objects ready
1127                  * don't apply this logic to OST specified with stripe_offset
1128                  */
1129                 if (i != 0 && sfs->os_fprecreated == 0 && speed == 0)
1130                         continue;
1131
1132                 o = lod_qos_declare_object_on(env, m, ost_idx, th);
1133                 if (IS_ERR(o)) {
1134                         CDEBUG(D_OTHER, "can't declare new object on #%u: %d\n",
1135                                ost_idx, (int) PTR_ERR(o));
1136                         continue;
1137                 }
1138
1139                 /*
1140                  * We've successfuly declared (reserved) an object
1141                  */
1142                 lod_qos_ost_in_use(env, stripe_num, ost_idx);
1143                 stripe[stripe_num] = o;
1144                 stripe_num++;
1145
1146                 /* We have enough stripes */
1147                 if (stripe_num == lo->ldo_stripenr)
1148                         GOTO(out, rc = 0);
1149         }
1150         if (speed < 2) {
1151                 /* Try again, allowing slower OSCs */
1152                 speed++;
1153                 goto repeat_find;
1154         }
1155
1156         /* If we were passed specific striping params, then a failure to
1157          * meet those requirements is an error, since we can't reallocate
1158          * that memory (it might be part of a larger array or something).
1159          *
1160          * We can only get here if lsm_stripe_count was originally > 1.
1161          */
1162         CERROR("can't lstripe objid "DFID": have %d want %u\n",
1163                PFID(lu_object_fid(lod2lu_obj(lo))), stripe_num,
1164                lo->ldo_stripenr);
1165         rc = -EFBIG;
1166 out:
1167         if (pool != NULL) {
1168                 up_read(&pool_tgt_rw_sem(pool));
1169                 /* put back ref got by lod_find_pool() */
1170                 lod_pool_putref(pool);
1171         }
1172
1173         RETURN(rc);
1174 }
1175
1176 /**
1177  * Check whether QoS allocation should be used.
1178  *
1179  * A simple helper to decide when QoS allocation should be used:
1180  * if it's just a single available target or the used space is
1181  * evenly distributed among the targets at the moment, then QoS
1182  * allocation algorithm should not be used.
1183  *
1184  * \param[in] lod       LOD device
1185  *
1186  * \retval 0            should not be used
1187  * \retval 1            should be used
1188  */
1189 static inline int lod_qos_is_usable(struct lod_device *lod)
1190 {
1191 #ifdef FORCE_QOS
1192         /* to be able to debug QoS code */
1193         return 1;
1194 #endif
1195
1196         /* Detect -EAGAIN early, before expensive lock is taken. */
1197         if (!lod->lod_qos.lq_dirty && lod->lod_qos.lq_same_space)
1198                 return 0;
1199
1200         if (lod->lod_desc.ld_active_tgt_count < 2)
1201                 return 0;
1202
1203         return 1;
1204 }
1205
1206 /**
1207  * Allocate a striping using an algorithm with weights.
1208  *
1209  * The function allocates OST objects to create a striping. The algorithm
1210  * used is based on weights (currently only using the free space), and it's
1211  * trying to ensure the space is used evenly by OSTs and OSSs. The striping
1212  * configuration (# of stripes, offset,
1213  * pool) is taken from the object and is prepared by the caller.
1214  * If LOV_USES_DEFAULT_STRIPE is not passed and prepared configuration can't
1215  * be met due to too few OSTs, then allocation fails. If the flag is
1216  * passed and less than 75% of the requested number of stripes can be
1217  * allocated, then allocation fails.
1218  * No concurrent allocation is allowed on the object and this must be
1219  * ensured by the caller. All the internal structures are protected by the
1220  * function.
1221  * The algorithm has two steps: find available OSTs and calucate their weights,
1222  * then select the OSTs the weights used as the probability. An OST with a
1223  * higher weight is proportionately more likely to be selected than one with
1224  * a lower weight.
1225  *
1226  * \param[in] env       execution environment for this thread
1227  * \param[in] lo        LOD object
1228  * \param[out] stripe   striping created
1229  * \param[in] flags     0 or LOV_USES_DEFAULT_STRIPE
1230  * \param[in] th        transaction handle
1231  *
1232  * \retval 0            on success
1233  * \retval -E2BIG       if no enough OSTs are found
1234  * \retval -EINVAL      requested offset is invalid
1235  * \retval negative     negated errno on error
1236  */
1237 static int lod_alloc_qos(const struct lu_env *env, struct lod_object *lo,
1238                          struct dt_object **stripe, int flags,
1239                          struct thandle *th)
1240 {
1241         struct lod_device   *m = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1242         struct obd_statfs   *sfs = &lod_env_info(env)->lti_osfs;
1243         struct lod_tgt_desc *ost;
1244         struct dt_object    *o;
1245         __u64                total_weight = 0;
1246         unsigned int         i;
1247         int                  rc = 0;
1248         __u32                nfound, good_osts;
1249         __u32                stripe_cnt = lo->ldo_stripenr;
1250         __u32                stripe_cnt_min;
1251         struct pool_desc    *pool = NULL;
1252         struct ost_pool    *osts;
1253         ENTRY;
1254
1255         stripe_cnt_min = min_stripe_count(stripe_cnt, flags);
1256         if (stripe_cnt_min < 1)
1257                 RETURN(-EINVAL);
1258
1259         if (lo->ldo_pool)
1260                 pool = lod_find_pool(m, lo->ldo_pool);
1261
1262         if (pool != NULL) {
1263                 down_read(&pool_tgt_rw_sem(pool));
1264                 osts = &(pool->pool_obds);
1265         } else {
1266                 osts = &(m->lod_pool_info);
1267         }
1268
1269         /* Detect -EAGAIN early, before expensive lock is taken. */
1270         if (!lod_qos_is_usable(m))
1271                 GOTO(out_nolock, rc = -EAGAIN);
1272
1273         /* Do actual allocation, use write lock here. */
1274         down_write(&m->lod_qos.lq_rw_sem);
1275
1276         /*
1277          * Check again, while we were sleeping on @lq_rw_sem things could
1278          * change.
1279          */
1280         if (!lod_qos_is_usable(m))
1281                 GOTO(out, rc = -EAGAIN);
1282
1283         rc = lod_qos_calc_ppo(m);
1284         if (rc)
1285                 GOTO(out, rc);
1286
1287         rc = lod_qos_ost_in_use_clear(env, lo->ldo_stripenr);
1288         if (rc)
1289                 GOTO(out, rc);
1290
1291         good_osts = 0;
1292         /* Find all the OSTs that are valid stripe candidates */
1293         for (i = 0; i < osts->op_count; i++) {
1294                 if (!cfs_bitmap_check(m->lod_ost_bitmap, osts->op_array[i]))
1295                         continue;
1296
1297                 rc = lod_statfs_and_check(env, m, osts->op_array[i], sfs);
1298                 if (rc) {
1299                         /* this OSP doesn't feel well */
1300                         continue;
1301                 }
1302
1303                 /*
1304                  * skip full devices
1305                  */
1306                 if (lod_qos_dev_is_full(sfs))
1307                         continue;
1308
1309                 /* Fail Check before osc_precreate() is called
1310                    so we can only 'fail' single OSC. */
1311                 if (OBD_FAIL_CHECK(OBD_FAIL_MDS_OSC_PRECREATE) &&
1312                                    osts->op_array[i] == 0)
1313                         continue;
1314
1315                 ost = OST_TGT(m,osts->op_array[i]);
1316                 ost->ltd_qos.ltq_usable = 1;
1317                 lod_qos_calc_weight(m, osts->op_array[i]);
1318                 total_weight += ost->ltd_qos.ltq_weight;
1319
1320                 good_osts++;
1321         }
1322
1323         QOS_DEBUG("found %d good osts\n", good_osts);
1324
1325         if (good_osts < stripe_cnt_min)
1326                 GOTO(out, rc = -EAGAIN);
1327
1328         /* We have enough osts */
1329         if (good_osts < stripe_cnt)
1330                 stripe_cnt = good_osts;
1331
1332         /* Find enough OSTs with weighted random allocation. */
1333         nfound = 0;
1334         while (nfound < stripe_cnt) {
1335                 __u64 rand, cur_weight;
1336
1337                 cur_weight = 0;
1338                 rc = -ENOSPC;
1339
1340                 if (total_weight) {
1341 #if BITS_PER_LONG == 32
1342                         rand = cfs_rand() % (unsigned)total_weight;
1343                         /* If total_weight > 32-bit, first generate the high
1344                          * 32 bits of the random number, then add in the low
1345                          * 32 bits (truncated to the upper limit, if needed) */
1346                         if (total_weight > 0xffffffffULL)
1347                                 rand = (__u64)(cfs_rand() %
1348                                         (unsigned)(total_weight >> 32)) << 32;
1349                         else
1350                                 rand = 0;
1351
1352                         if (rand == (total_weight & 0xffffffff00000000ULL))
1353                                 rand |= cfs_rand() % (unsigned)total_weight;
1354                         else
1355                                 rand |= cfs_rand();
1356
1357 #else
1358                         rand = ((__u64)cfs_rand() << 32 | cfs_rand()) %
1359                                 total_weight;
1360 #endif
1361                 } else {
1362                         rand = 0;
1363                 }
1364
1365                 /* On average, this will hit larger-weighted osts more often.
1366                    0-weight osts will always get used last (only when rand=0) */
1367                 for (i = 0; i < osts->op_count; i++) {
1368                         __u32 idx = osts->op_array[i];
1369
1370                         if (!cfs_bitmap_check(m->lod_ost_bitmap, idx))
1371                                 continue;
1372
1373                         ost = OST_TGT(m,idx);
1374
1375                         if (!ost->ltd_qos.ltq_usable)
1376                                 continue;
1377
1378                         cur_weight += ost->ltd_qos.ltq_weight;
1379                         QOS_DEBUG("stripe_cnt=%d nfound=%d cur_weight="LPU64
1380                                   " rand="LPU64" total_weight="LPU64"\n",
1381                                   stripe_cnt, nfound, cur_weight, rand,
1382                                   total_weight);
1383
1384                         if (cur_weight < rand)
1385                                 continue;
1386
1387                         QOS_DEBUG("stripe=%d to idx=%d\n", nfound, idx);
1388
1389                         /*
1390                          * do not put >1 objects on a single OST
1391                          */
1392                         if (lod_qos_is_ost_used(env, idx, nfound))
1393                                 continue;
1394                         lod_qos_ost_in_use(env, nfound, idx);
1395
1396                         o = lod_qos_declare_object_on(env, m, idx, th);
1397                         if (IS_ERR(o)) {
1398                                 QOS_DEBUG("can't declare object on #%u: %d\n",
1399                                           idx, (int) PTR_ERR(o));
1400                                 continue;
1401                         }
1402                         stripe[nfound++] = o;
1403                         lod_qos_used(m, osts, idx, &total_weight);
1404                         rc = 0;
1405                         break;
1406                 }
1407
1408                 if (rc) {
1409                         /* no OST found on this iteration, give up */
1410                         break;
1411                 }
1412         }
1413
1414         if (unlikely(nfound != stripe_cnt)) {
1415                 /*
1416                  * when the decision to use weighted algorithm was made
1417                  * we had enough appropriate OSPs, but this state can
1418                  * change anytime (no space on OST, broken connection, etc)
1419                  * so it's possible OSP won't be able to provide us with
1420                  * an object due to just changed state
1421                  */
1422                 LCONSOLE_INFO("wanted %d, found %d\n", stripe_cnt, nfound);
1423                 for (i = 0; i < nfound; i++) {
1424                         LASSERT(stripe[i] != NULL);
1425                         lu_object_put(env, &stripe[i]->do_lu);
1426                         stripe[i] = NULL;
1427                 }
1428
1429                 /* makes sense to rebalance next time */
1430                 m->lod_qos.lq_dirty = 1;
1431                 m->lod_qos.lq_same_space = 0;
1432
1433                 rc = -EAGAIN;
1434         }
1435
1436 out:
1437         up_write(&m->lod_qos.lq_rw_sem);
1438
1439 out_nolock:
1440         if (pool != NULL) {
1441                 up_read(&pool_tgt_rw_sem(pool));
1442                 /* put back ref got by lod_find_pool() */
1443                 lod_pool_putref(pool);
1444         }
1445
1446         RETURN(rc);
1447 }
1448
1449 /**
1450  * Find largest stripe count the caller can use.
1451  *
1452  * Find the maximal possible stripe count not greater than \a stripe_count.
1453  * Sometimes suggested stripecount can't be reached for a number of reasons:
1454  * lack of enough active OSTs or the backend does not support EAs that large.
1455  * If the passed one is 0, then the filesystem's default one is used.
1456  *
1457  * \param[in] lod       LOD device
1458  * \param[in] magic     the format if striping
1459  * \param[in] stripe_count      count the caller would like to use
1460  *
1461  * \retval              the maximum usable stripe count
1462  */
1463 static __u16 lod_get_stripecnt(struct lod_device *lod, __u32 magic,
1464                                __u16 stripe_count)
1465 {
1466         __u32 max_stripes = LOV_MAX_STRIPE_COUNT_OLD;
1467
1468         if (!stripe_count)
1469                 stripe_count = lod->lod_desc.ld_default_stripe_count;
1470         if (stripe_count > lod->lod_desc.ld_active_tgt_count)
1471                 stripe_count = lod->lod_desc.ld_active_tgt_count;
1472         if (!stripe_count)
1473                 stripe_count = 1;
1474
1475         /* stripe count is based on whether OSD can handle larger EA sizes */
1476         if (lod->lod_osd_max_easize > 0)
1477                 max_stripes = lov_mds_md_max_stripe_count(
1478                         lod->lod_osd_max_easize, magic);
1479
1480         return (stripe_count < max_stripes) ? stripe_count : max_stripes;
1481 }
1482
1483 /**
1484  * Create in-core respresentation for a fully-defined striping
1485  *
1486  * When the caller passes a fully-defined striping (i.e. everything including
1487  * OST object FIDs are defined), then we still need to instantiate LU-cache
1488  * with the objects representing the stripes defined. This function completes
1489  * that task.
1490  *
1491  * \param[in] env       execution environment for this thread
1492  * \param[in] mo        LOD object
1493  * \param[in] buf       buffer containing the striping
1494  *
1495  * \retval 0            on success
1496  * \retval negative     negated errno on error
1497  */
1498 static int lod_use_defined_striping(const struct lu_env *env,
1499                                     struct lod_object *mo,
1500                                     const struct lu_buf *buf)
1501 {
1502         struct lov_mds_md_v1   *v1 = buf->lb_buf;
1503         struct lov_mds_md_v3   *v3 = buf->lb_buf;
1504         struct lov_ost_data_v1 *objs;
1505         __u32                   magic;
1506         int                     rc = 0;
1507         ENTRY;
1508
1509         magic = le32_to_cpu(v1->lmm_magic);
1510         if (magic == LOV_MAGIC_V1_DEF) {
1511                 magic = LOV_MAGIC_V1;
1512                 objs = &v1->lmm_objects[0];
1513         } else if (magic == LOV_MAGIC_V3_DEF) {
1514                 magic = LOV_MAGIC_V3;
1515                 objs = &v3->lmm_objects[0];
1516                 lod_object_set_pool(mo, v3->lmm_pool_name);
1517         } else {
1518                 GOTO(out, rc = -EINVAL);
1519         }
1520
1521         mo->ldo_pattern = le32_to_cpu(v1->lmm_pattern);
1522         mo->ldo_stripe_size = le32_to_cpu(v1->lmm_stripe_size);
1523         mo->ldo_stripenr = le16_to_cpu(v1->lmm_stripe_count);
1524         mo->ldo_layout_gen = le16_to_cpu(v1->lmm_layout_gen);
1525
1526         /* fixup for released file before object initialization */
1527         if (mo->ldo_pattern & LOV_PATTERN_F_RELEASED) {
1528                 mo->ldo_released_stripenr = mo->ldo_stripenr;
1529                 mo->ldo_stripenr = 0;
1530         }
1531
1532         LASSERT(buf->lb_len >= lov_mds_md_size(mo->ldo_stripenr, magic));
1533
1534         if (mo->ldo_stripenr > 0)
1535                 rc = lod_initialize_objects(env, mo, objs);
1536
1537 out:
1538         RETURN(rc);
1539 }
1540
1541 /**
1542  * Parse suggested striping configuration.
1543  *
1544  * The caller gets a suggested striping configuration from a number of sources
1545  * including per-directory default and applications. Then it needs to verify
1546  * the suggested striping is valid, apply missing bits and store the resulting
1547  * configuration in the object to be used by the allocator later. Must not be
1548  * called concurrently against the same object. It's OK to provide a
1549  * fully-defined striping.
1550  *
1551  * \param[in] env       execution environment for this thread
1552  * \param[in] lo        LOD object
1553  * \param[in] buf       buffer containing the striping
1554  *
1555  * \retval 0            on success
1556  * \retval negative     negated errno on error
1557  */
1558 static int lod_qos_parse_config(const struct lu_env *env,
1559                                 struct lod_object *lo,
1560                                 const struct lu_buf *buf)
1561 {
1562         struct lod_device     *d = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
1563         struct lov_user_md_v1 *v1 = NULL;
1564         struct lov_user_md_v3 *v3 = NULL;
1565         struct pool_desc      *pool;
1566         __u32                  magic;
1567         int                    rc;
1568         ENTRY;
1569
1570         if (buf == NULL || buf->lb_buf == NULL || buf->lb_len == 0)
1571                 RETURN(0);
1572
1573         v1 = buf->lb_buf;
1574         magic = v1->lmm_magic;
1575
1576         if (magic == __swab32(LOV_USER_MAGIC_V1)) {
1577                 lustre_swab_lov_user_md_v1(v1);
1578                 magic = v1->lmm_magic;
1579         } else if (magic == __swab32(LOV_USER_MAGIC_V3)) {
1580                 v3 = buf->lb_buf;
1581                 lustre_swab_lov_user_md_v3(v3);
1582                 magic = v3->lmm_magic;
1583         }
1584
1585         if (unlikely(magic != LOV_MAGIC_V1 && magic != LOV_MAGIC_V3)) {
1586                 /* try to use as fully defined striping */
1587                 rc = lod_use_defined_striping(env, lo, buf);
1588                 RETURN(rc);
1589         }
1590
1591         if (unlikely(buf->lb_len < sizeof(*v1))) {
1592                 CERROR("wrong size: %u\n", (unsigned) buf->lb_len);
1593                 RETURN(-EINVAL);
1594         }
1595
1596         v1->lmm_magic = magic;
1597         if (v1->lmm_pattern == 0)
1598                 v1->lmm_pattern = LOV_PATTERN_RAID0;
1599         if (lov_pattern(v1->lmm_pattern) != LOV_PATTERN_RAID0) {
1600                 CERROR("invalid pattern: %x\n", v1->lmm_pattern);
1601                 RETURN(-EINVAL);
1602         }
1603         lo->ldo_pattern = v1->lmm_pattern;
1604
1605         if (v1->lmm_stripe_size)
1606                 lo->ldo_stripe_size = v1->lmm_stripe_size;
1607         if (lo->ldo_stripe_size & (LOV_MIN_STRIPE_SIZE - 1))
1608                 lo->ldo_stripe_size = LOV_MIN_STRIPE_SIZE;
1609
1610         if (v1->lmm_stripe_count)
1611                 lo->ldo_stripenr = v1->lmm_stripe_count;
1612
1613         if ((v1->lmm_stripe_offset >= d->lod_desc.ld_tgt_count) &&
1614             (v1->lmm_stripe_offset != (typeof(v1->lmm_stripe_offset))(-1))) {
1615                 CERROR("invalid offset: %x\n", v1->lmm_stripe_offset);
1616                 RETURN(-EINVAL);
1617         }
1618         lo->ldo_def_stripe_offset = v1->lmm_stripe_offset;
1619
1620         CDEBUG(D_OTHER, "lsm: %u size, %u stripes, %u offset\n",
1621                v1->lmm_stripe_size, v1->lmm_stripe_count,
1622                v1->lmm_stripe_offset);
1623
1624         if (v1->lmm_magic == LOV_MAGIC_V3) {
1625                 if (buf->lb_len < sizeof(*v3)) {
1626                         CERROR("wrong size: %u\n", (unsigned) buf->lb_len);
1627                         RETURN(-EINVAL);
1628                 }
1629
1630                 v3 = buf->lb_buf;
1631                 lod_object_set_pool(lo, v3->lmm_pool_name);
1632
1633                 /* In the function below, .hs_keycmp resolves to
1634                  * pool_hashkey_keycmp() */
1635                 /* coverity[overrun-buffer-val] */
1636                 pool = lod_find_pool(d, v3->lmm_pool_name);
1637                 if (pool != NULL) {
1638                         if (lo->ldo_def_stripe_offset !=
1639                             (typeof(v1->lmm_stripe_offset))(-1)) {
1640                                 rc = lo->ldo_def_stripe_offset;
1641                                 rc = lod_check_index_in_pool(rc, pool);
1642                                 if (rc < 0) {
1643                                         lod_pool_putref(pool);
1644                                         CERROR("invalid offset\n");
1645                                         RETURN(-EINVAL);
1646                                 }
1647                         }
1648
1649                         if (lo->ldo_stripenr > pool_tgt_count(pool))
1650                                 lo->ldo_stripenr= pool_tgt_count(pool);
1651
1652                         lod_pool_putref(pool);
1653                 }
1654         } else
1655                 lod_object_set_pool(lo, NULL);
1656
1657         /* fixup for released file */
1658         if (lo->ldo_pattern & LOV_PATTERN_F_RELEASED) {
1659                 lo->ldo_released_stripenr = lo->ldo_stripenr;
1660                 lo->ldo_stripenr = 0;
1661         }
1662
1663         RETURN(0);
1664 }
1665
1666 /**
1667  * Create a striping for an obejct.
1668  *
1669  * The function creates a new striping for the object. A buffer containing
1670  * configuration hints can be provided optionally. The function tries QoS
1671  * algorithm first unless free space is distributed evenly among OSTs, but
1672  * by default RR algorithm is preferred due to internal concurrency (QoS is
1673  * serialized). The caller must ensure no concurrent calls to the function
1674  * are made against the same object.
1675  *
1676  * \param[in] env       execution environment for this thread
1677  * \param[in] lo        LOD object
1678  * \param[in] attr      attributes OST objects will be declared with
1679  * \param[in] buf       suggested striping configuration or NULL
1680  * \param[in] th        transaction handle
1681  *
1682  * \retval 0            on success
1683  * \retval negative     negated errno on error
1684  */
1685 int lod_qos_prep_create(const struct lu_env *env, struct lod_object *lo,
1686                         struct lu_attr *attr, const struct lu_buf *buf,
1687                         struct thandle *th)
1688 {
1689         struct lod_device      *d = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
1690         struct dt_object      **stripe;
1691         int                     stripe_len;
1692         int                     flag = LOV_USES_ASSIGNED_STRIPE;
1693         int                     i, rc;
1694         ENTRY;
1695
1696         LASSERT(lo);
1697
1698         /* no OST available */
1699         /* XXX: should we be waiting a bit to prevent failures during
1700          * cluster initialization? */
1701         if (d->lod_ostnr == 0)
1702                 GOTO(out, rc = -EIO);
1703
1704         /*
1705          * by this time, the object's ldo_stripenr and ldo_stripe_size
1706          * contain default value for striping: taken from the parent
1707          * or from filesystem defaults
1708          *
1709          * in case the caller is passing lovea with new striping config,
1710          * we may need to parse lovea and apply new configuration
1711          */
1712         rc = lod_qos_parse_config(env, lo, buf);
1713         if (rc)
1714                 GOTO(out, rc);
1715
1716         /* A released file is being created */
1717         if (lo->ldo_stripenr == 0)
1718                 GOTO(out, rc = 0);
1719
1720         if (likely(lo->ldo_stripe == NULL)) {
1721                 /*
1722                  * no striping has been created so far
1723                  */
1724                 LASSERT(lo->ldo_stripenr > 0);
1725                 /*
1726                  * statfs and check OST targets now, since ld_active_tgt_count
1727                  * could be changed if some OSTs are [de]activated manually.
1728                  */
1729                 lod_qos_statfs_update(env, d);
1730                 lo->ldo_stripenr = lod_get_stripecnt(d, LOV_MAGIC,
1731                                 lo->ldo_stripenr);
1732
1733                 stripe_len = lo->ldo_stripenr;
1734                 OBD_ALLOC(stripe, sizeof(stripe[0]) * stripe_len);
1735                 if (stripe == NULL)
1736                         GOTO(out, rc = -ENOMEM);
1737
1738                 lod_getref(&d->lod_ost_descs);
1739                 /* XXX: support for non-0 files w/o objects */
1740                 CDEBUG(D_OTHER, "tgt_count %d stripenr %d\n",
1741                                 d->lod_desc.ld_tgt_count, stripe_len);
1742                 if (lo->ldo_def_stripe_offset >= d->lod_desc.ld_tgt_count) {
1743                         rc = lod_alloc_qos(env, lo, stripe, flag, th);
1744                         if (rc == -EAGAIN)
1745                                 rc = lod_alloc_rr(env, lo, stripe, flag, th);
1746                 } else {
1747                         rc = lod_alloc_specific(env, lo, stripe, flag, th);
1748                 }
1749                 lod_putref(d, &d->lod_ost_descs);
1750
1751                 if (rc < 0) {
1752                         for (i = 0; i < stripe_len; i++)
1753                                 if (stripe[i] != NULL)
1754                                         lu_object_put(env, &stripe[i]->do_lu);
1755
1756                         OBD_FREE(stripe, sizeof(stripe[0]) * stripe_len);
1757                         lo->ldo_stripenr = 0;
1758                 } else {
1759                         lo->ldo_stripe = stripe;
1760                         lo->ldo_stripes_allocated = stripe_len;
1761                 }
1762         } else {
1763                 /*
1764                  * lod_qos_parse_config() found supplied buf as a predefined
1765                  * striping (not a hint), so it allocated all the object
1766                  * now we need to create them
1767                  */
1768                 for (i = 0; i < lo->ldo_stripenr; i++) {
1769                         struct dt_object  *o;
1770
1771                         o = lo->ldo_stripe[i];
1772                         LASSERT(o);
1773
1774                         rc = dt_declare_create(env, o, attr, NULL, NULL, th);
1775                         if (rc) {
1776                                 CERROR("can't declare create: %d\n", rc);
1777                                 break;
1778                         }
1779                 }
1780         }
1781
1782 out:
1783         RETURN(rc);
1784 }
1785