Whamcloud - gitweb
LU-17662 osd-zfs: Support for ZFS 2.2.3
[fs/lustre-release.git] / lustre / mdt / mdt_coordinator.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 (c) 2011, 2012 Commissariat a l'energie atomique et aux energies
24  *                          alternatives
25  *
26  * Copyright (c) 2013, 2017, Intel Corporation.
27  * Use is subject to license terms.
28  */
29 /*
30  * lustre/mdt/mdt_coordinator.c
31  *
32  * Lustre HSM Coordinator
33  *
34  * Author: Jacques-Charles Lafoucriere <jacques-charles.lafoucriere@cea.fr>
35  * Author: Aurelien Degremont <aurelien.degremont@cea.fr>
36  * Author: Thomas Leibovici <thomas.leibovici@cea.fr>
37  */
38
39 #define DEBUG_SUBSYSTEM S_MDS
40
41 #include <linux/kthread.h>
42 #include <linux/kernel.h>
43 #include <obd_support.h>
44 #include <lustre_export.h>
45 #include <obd.h>
46 #include <lprocfs_status.h>
47 #include <lustre_log.h>
48 #include <lustre_kernelcomm.h>
49 #include "mdt_internal.h"
50
51 /**
52  * get obj and HSM attributes on a fid
53  * \param mti [IN] context
54  * \param fid [IN] object fid
55  * \param hsm [OUT] HSM meta data
56  * \retval obj or error (-ENOENT if not found)
57  */
58 struct mdt_object *mdt_hsm_get_md_hsm(struct mdt_thread_info *mti,
59                                       const struct lu_fid *fid,
60                                       struct md_hsm *hsm)
61 {
62         struct md_attr          *ma;
63         struct mdt_object       *obj;
64         int                      rc;
65         ENTRY;
66
67         ma = &mti->mti_attr;
68         ma->ma_need = MA_HSM;
69         ma->ma_valid = 0;
70
71         /* find object by FID */
72         obj = mdt_object_find(mti->mti_env, mti->mti_mdt, fid);
73         if (IS_ERR(obj))
74                 RETURN(obj);
75
76         if (!mdt_object_exists(obj)) {
77                 /* no more object */
78                 mdt_object_put(mti->mti_env, obj);
79                 RETURN(ERR_PTR(-ENOENT));
80         }
81
82         rc = mdt_attr_get_complex(mti, obj, ma);
83         if (rc) {
84                 mdt_object_put(mti->mti_env, obj);
85                 RETURN(ERR_PTR(rc));
86         }
87
88         if (ma->ma_valid & MA_HSM)
89                 *hsm = ma->ma_hsm;
90         else
91                 memset(hsm, 0, sizeof(*hsm));
92         ma->ma_valid = 0;
93         RETURN(obj);
94 }
95
96 void mdt_hsm_dump_hal(int level, const char *prefix,
97                       struct hsm_action_list *hal)
98 {
99         int                      i, sz;
100         struct hsm_action_item  *hai;
101         char                     buf[12];
102
103         CDEBUG(level, "%s: HAL header: version %X count %d"
104                       " archive_id %d flags %#llx\n",
105                prefix, hal->hal_version, hal->hal_count,
106                hal->hal_archive_id, hal->hal_flags);
107
108         hai = hai_first(hal);
109         for (i = 0; i < hal->hal_count; i++) {
110                 sz = hai->hai_len - sizeof(*hai);
111                 CDEBUG(level, "%s %d: fid="DFID" dfid="DFID
112                        " cookie=%#llx"
113                        " action=%s extent=%#llx-%#llx gid=%#llx"
114                        " datalen=%d data=[%s]\n",
115                        prefix, i,
116                        PFID(&hai->hai_fid), PFID(&hai->hai_dfid),
117                        hai->hai_cookie,
118                        hsm_copytool_action2name(hai->hai_action),
119                        hai->hai_extent.offset,
120                        hai->hai_extent.length,
121                        hai->hai_gid, sz,
122                        hai_dump_data_field(hai, buf, sizeof(buf)));
123                 hai = hai_next(hai);
124         }
125 }
126
127 /**
128  * data passed to llog_cat_process() callback
129  * to scan requests and take actions
130  */
131 struct hsm_scan_request {
132         int                      hal_sz;
133         int                      hal_used_sz;
134         struct hsm_action_list  *hal;
135 };
136
137 struct hsm_scan_data {
138         struct mdt_thread_info  *hsd_mti;
139         char                     hsd_fsname[MTI_NAME_MAXLEN + 1];
140         /* are we scanning the logs for housekeeping, or just looking
141          * for new work?
142          */
143         bool                     hsd_housekeeping;
144         bool                     hsd_one_restore;
145         u32                      hsd_start_cat_idx;
146         u32                      hsd_start_rec_idx;
147         int                      hsd_action_count;
148         int                      hsd_request_len; /* array alloc len */
149         int                      hsd_request_count; /* array used count */
150         struct hsm_scan_request *hsd_request;
151 };
152
153 static int mdt_cdt_waiting_cb(const struct lu_env *env,
154                               struct mdt_device *mdt,
155                               struct llog_handle *llh,
156                               struct llog_agent_req_rec *larr,
157                               struct hsm_scan_data *hsd)
158 {
159         struct coordinator *cdt = &mdt->mdt_coordinator;
160         struct hsm_scan_request *request;
161         struct hsm_action_item *hai;
162         size_t hai_size;
163         u32 archive_id;
164         bool wrapped;
165         int i;
166
167         /* Are agents full? */
168         if (atomic_read(&cdt->cdt_request_count) >= cdt->cdt_max_requests)
169                 RETURN(hsd->hsd_housekeeping ? 0 : LLOG_PROC_BREAK);
170
171         if (hsd->hsd_action_count + atomic_read(&cdt->cdt_request_count) >=
172             cdt->cdt_max_requests) {
173                 /* We cannot send any more request
174                  *
175                  *                     *** SPECIAL CASE ***
176                  *
177                  * Restore requests are too important not to schedule at least
178                  * one, everytime we can.
179                  */
180                 if (larr->arr_hai.hai_action != HSMA_RESTORE ||
181                     hsd->hsd_one_restore)
182                         RETURN(hsd->hsd_housekeeping ? 0 : LLOG_PROC_BREAK);
183         }
184
185         hai_size = round_up(larr->arr_hai.hai_len, 8);
186         archive_id = larr->arr_archive_id;
187
188         /* Can we add this action to one of the existing HALs in hsd. */
189         request = NULL;
190         for (i = 0; i < hsd->hsd_request_count; i++) {
191                 if (hsd->hsd_request[i].hal->hal_archive_id == archive_id &&
192                     hsd->hsd_request[i].hal_used_sz + hai_size <=
193                     LDLM_MAXREQSIZE) {
194                         request = &hsd->hsd_request[i];
195                         break;
196                 }
197         }
198
199         /* Are we trying to force-schedule a request? */
200         if (hsd->hsd_action_count + atomic_read(&cdt->cdt_request_count) >=
201             cdt->cdt_max_requests) {
202                 /* Is there really no compatible hsm_scan_request? */
203                 if (!request) {
204                         for (i -= 1; i >= 0; i--) {
205                                 if (hsd->hsd_request[i].hal->hal_archive_id ==
206                                     archive_id) {
207                                         request = &hsd->hsd_request[i];
208                                         break;
209                                 }
210                         }
211                 }
212
213                 /* Make room for the hai */
214                 if (request) {
215                         /* Discard the last hai until there is enough space */
216                         do {
217                                 request->hal->hal_count--;
218
219                                 hai = hai_first(request->hal);
220                                 for (i = 0; i < request->hal->hal_count; i++)
221                                         hai = hai_next(hai);
222                                 request->hal_used_sz -=
223                                         round_up(hai->hai_len, 8);
224                                 hsd->hsd_action_count--;
225                         } while (request->hal_used_sz + hai_size >
226                                  LDLM_MAXREQSIZE);
227                 } else if (hsd->hsd_housekeeping) {
228                         struct hsm_scan_request *tmp;
229
230                         /* Discard the (whole) last hal */
231                         hsd->hsd_request_count--;
232                         LASSERT(hsd->hsd_request_count >= 0);
233                         tmp = &hsd->hsd_request[hsd->hsd_request_count];
234                         hsd->hsd_action_count -= tmp->hal->hal_count;
235                         LASSERT(hsd->hsd_action_count >= 0);
236                         OBD_FREE(tmp->hal, tmp->hal_sz);
237                 } else {
238                         /* Bailing out, this code path is too hot */
239                         RETURN(LLOG_PROC_BREAK);
240
241                 }
242         }
243
244         if (!request) {
245                 size_t count = round_up(MTI_NAME_MAXLEN + 1, 8) + 2 * hai_size;
246                 struct hsm_action_list *hal;
247
248                 LASSERT(hsd->hsd_request_count < hsd->hsd_request_len);
249                 request = &hsd->hsd_request[hsd->hsd_request_count];
250
251                 /* allocates hai vector size just needs to be large
252                  * enough */
253                 request->hal_sz = sizeof(*request->hal) + count;
254                 OBD_ALLOC_LARGE(hal, request->hal_sz);
255                 if (!hal)
256                         RETURN(-ENOMEM);
257
258                 hal->hal_version = HAL_VERSION;
259                 strscpy(hal->hal_fsname, hsd->hsd_fsname, MTI_NAME_MAXLEN + 1);
260                 hal->hal_archive_id = larr->arr_archive_id;
261                 hal->hal_flags = larr->arr_flags;
262                 hal->hal_count = 0;
263                 request->hal_used_sz = hal_size(hal);
264                 request->hal = hal;
265                 hsd->hsd_request_count++;
266         } else if (request->hal_sz < request->hal_used_sz + hai_size) {
267                 /* Not enough room, need an extension */
268                 void *hal_buffer;
269                 int sz;
270
271                 sz = min_t(int, 2 * request->hal_sz, LDLM_MAXREQSIZE);
272                 LASSERT(request->hal_used_sz + hai_size < sz);
273
274                 OBD_ALLOC_LARGE(hal_buffer, sz);
275                 if (!hal_buffer)
276                         RETURN(-ENOMEM);
277
278                 memcpy(hal_buffer, request->hal, request->hal_used_sz);
279                 OBD_FREE_LARGE(request->hal, request->hal_sz);
280                 request->hal = hal_buffer;
281                 request->hal_sz = sz;
282         }
283
284         hai = hai_first(request->hal);
285         for (i = 0; i < request->hal->hal_count; i++)
286                 hai = hai_next(hai);
287
288         memcpy(hai, &larr->arr_hai, larr->arr_hai.hai_len);
289
290         request->hal_used_sz += hai_size;
291         request->hal->hal_count++;
292
293         hsd->hsd_action_count++;
294
295         switch (hai->hai_action) {
296         case HSMA_CANCEL:
297                 break;
298         case HSMA_RESTORE:
299                 hsd->hsd_one_restore = true;
300                 fallthrough;
301         default:
302                 cdt_agent_record_hash_add(cdt, hai->hai_cookie,
303                                           llh->lgh_hdr->llh_cat_idx,
304                                           larr->arr_hdr.lrh_index);
305         }
306
307         wrapped = llh->lgh_hdr->llh_cat_idx >= llh->lgh_last_idx &&
308                   llh->lgh_hdr->llh_count > 1;
309         if ((!wrapped && llh->lgh_hdr->llh_cat_idx > hsd->hsd_start_cat_idx) ||
310             (wrapped && llh->lgh_hdr->llh_cat_idx < hsd->hsd_start_cat_idx) ||
311             (llh->lgh_hdr->llh_cat_idx == hsd->hsd_start_cat_idx &&
312              larr->arr_hdr.lrh_index > hsd->hsd_start_rec_idx)) {
313                 hsd->hsd_start_cat_idx = llh->lgh_hdr->llh_cat_idx;
314                 hsd->hsd_start_rec_idx = larr->arr_hdr.lrh_index;
315         }
316
317         RETURN(0);
318 }
319
320 static int mdt_cdt_started_cb(const struct lu_env *env,
321                               struct mdt_device *mdt,
322                               struct llog_handle *llh,
323                               struct llog_agent_req_rec *larr,
324                               struct hsm_scan_data *hsd)
325 {
326         struct coordinator *cdt = &mdt->mdt_coordinator;
327         struct hsm_action_item *hai = &larr->arr_hai;
328         struct cdt_agent_req *car;
329         time64_t now = ktime_get_real_seconds();
330         time64_t last;
331         enum changelog_rec_flags clf_flags;
332         int rc;
333
334         if (!hsd->hsd_housekeeping)
335                 RETURN(0);
336
337         /* we search for a running request
338          * error may happen if coordinator crashes or stopped
339          * with running request
340          */
341         car = mdt_cdt_find_request(cdt, hai->hai_cookie);
342         if (car == NULL) {
343                 last = larr->arr_req_change;
344         } else {
345                 last = car->car_req_update;
346         }
347
348         /* test if request too long, if yes cancel it
349          * the same way the copy tool acknowledge a cancel request */
350         if (now <= last + cdt->cdt_active_req_timeout)
351                 GOTO(out_car, rc = 0);
352
353         dump_llog_agent_req_rec("request timed out, start cleaning", larr);
354
355         if (car != NULL) {
356                 car->car_req_update = now;
357                 mdt_hsm_agent_update_statistics(cdt, 0, 1, 0, &car->car_uuid);
358                 /* Remove car from memory list (LU-9075) */
359                 mdt_cdt_remove_request(cdt, hai->hai_cookie);
360         }
361
362         /* Emit a changelog record for the failed action.*/
363         clf_flags = 0;
364         hsm_set_cl_error(&clf_flags, ECANCELED);
365
366         switch (hai->hai_action) {
367         case HSMA_ARCHIVE:
368                 hsm_set_cl_event(&clf_flags, HE_ARCHIVE);
369                 break;
370         case HSMA_RESTORE:
371                 hsm_set_cl_event(&clf_flags, HE_RESTORE);
372                 break;
373         case HSMA_REMOVE:
374                 hsm_set_cl_event(&clf_flags, HE_REMOVE);
375                 break;
376         case HSMA_CANCEL:
377                 hsm_set_cl_event(&clf_flags, HE_CANCEL);
378                 break;
379         default:
380                 /* Unknown record type, skip changelog. */
381                 clf_flags = 0;
382                 break;
383         }
384
385         if (clf_flags != 0)
386                 mo_changelog(env, CL_HSM, clf_flags, mdt->mdt_child,
387                              &hai->hai_fid);
388
389         if (hai->hai_action == HSMA_RESTORE)
390                 cdt_restore_handle_del(hsd->hsd_mti, cdt, &hai->hai_fid);
391
392         larr->arr_status = ARS_CANCELED;
393         larr->arr_req_change = now;
394         rc = llog_write(hsd->hsd_mti->mti_env, llh, &larr->arr_hdr,
395                         larr->arr_hdr.lrh_index);
396         if (rc < 0) {
397                 CERROR("%s: cannot update agent log: rc = %d\n",
398                        mdt_obd_name(mdt), rc);
399                 rc = LLOG_DEL_RECORD;
400         }
401
402         /* ct has completed a request, so a slot is available,
403          * signal the coordinator to find new work */
404         mdt_hsm_cdt_event(cdt);
405 out_car:
406         if (car != NULL)
407                 mdt_cdt_put_request(car);
408
409         RETURN(rc);
410 }
411
412 /**
413  *  llog_cat_process() callback, used to:
414  *  - find waiting request and start action
415  *  - purge canceled and done requests
416  * \param env [IN] environment
417  * \param llh [IN] llog handle
418  * \param hdr [IN] llog record
419  * \param data [IN/OUT] cb data = struct hsm_scan_data
420  * \retval 0 success
421  * \retval -ve failure
422  */
423 static int mdt_coordinator_cb(const struct lu_env *env,
424                               struct llog_handle *llh,
425                               struct llog_rec_hdr *hdr,
426                               void *data)
427 {
428         struct llog_agent_req_rec *larr = (struct llog_agent_req_rec *)hdr;
429         struct hsm_scan_data *hsd = data;
430         struct mdt_device *mdt = hsd->hsd_mti->mti_mdt;
431         struct coordinator *cdt = &mdt->mdt_coordinator;
432         ENTRY;
433
434         larr = (struct llog_agent_req_rec *)hdr;
435         dump_llog_agent_req_rec("mdt_coordinator_cb(): ", larr);
436         switch (larr->arr_status) {
437         case ARS_WAITING:
438                 RETURN(mdt_cdt_waiting_cb(env, mdt, llh, larr, hsd));
439         case ARS_STARTED:
440                 RETURN(mdt_cdt_started_cb(env, mdt, llh, larr, hsd));
441         default:
442                 if (!hsd->hsd_housekeeping)
443                         RETURN(0);
444
445                 if ((larr->arr_req_change + cdt->cdt_grace_delay) <
446                     ktime_get_real_seconds()) {
447                         cdt_agent_record_hash_del(cdt,
448                                                   larr->arr_hai.hai_cookie);
449                         RETURN(LLOG_DEL_RECORD);
450                 }
451
452                 RETURN(0);
453         }
454 }
455
456 static void cdt_crh_free(struct rcu_head *head)
457 {
458         struct cdt_restore_handle *crh;
459
460         crh = container_of(head, struct cdt_restore_handle, crh_rcu);
461         OBD_SLAB_FREE_PTR(crh, mdt_hsm_cdt_kmem);
462 }
463
464 static void
465 cdt_crh_put(struct cdt_restore_handle *crh, struct mdt_thread_info *cdt_mti)
466 {
467         if (atomic_dec_and_test(&crh->crh_refc)) {
468                 /* XXX We pass a NULL object since the restore handle does not
469                  * keep a reference on the object being restored.
470                  */
471                 if (lustre_handle_is_used(&crh->crh_lh.mlh_reg_lh))
472                         mdt_object_unlock(cdt_mti, NULL, &crh->crh_lh, 1);
473                 call_rcu(&crh->crh_rcu, cdt_crh_free);
474         }
475 }
476
477 static void crh_free_hash(void *vcrh, void *vcdt_mti)
478 {
479         struct cdt_restore_handle *crh = vcrh;
480         struct mdt_thread_info *cdt_mti = vcdt_mti;
481
482         /* put last reference */
483         cdt_crh_put(crh, cdt_mti);
484 }
485
486 static const struct rhashtable_params crh_hash_params = {
487         .key_len        = sizeof(struct lu_fid),
488         .key_offset     = offsetof(struct cdt_restore_handle, crh_fid),
489         .head_offset    = offsetof(struct cdt_restore_handle, crh_hash),
490         .hashfn         = lu_fid_hash,
491         .automatic_shrinking = true,
492 };
493
494 /* Release the ressource used by the coordinator. Called when the
495  * coordinator is stopping. */
496 static void mdt_hsm_cdt_cleanup(struct mdt_device *mdt)
497 {
498         struct coordinator              *cdt = &mdt->mdt_coordinator;
499         struct cdt_agent_req            *car, *tmp1;
500         struct hsm_agent                *ha, *tmp2;
501         struct mdt_thread_info          *cdt_mti;
502
503         /* start cleaning */
504         down_write(&cdt->cdt_request_lock);
505         list_for_each_entry_safe(car, tmp1, &cdt->cdt_request_list,
506                                  car_request_list) {
507                 cfs_hash_del(cdt->cdt_request_cookie_hash,
508                              &car->car_hai->hai_cookie,
509                              &car->car_cookie_hash);
510                 list_del(&car->car_request_list);
511                 mdt_cdt_put_request(car);
512         }
513         up_write(&cdt->cdt_request_lock);
514
515         down_write(&cdt->cdt_agent_lock);
516         list_for_each_entry_safe(ha, tmp2, &cdt->cdt_agents, ha_list) {
517                 list_del(&ha->ha_list);
518                 if (ha->ha_archive_cnt != 0)
519                         OBD_FREE_PTR_ARRAY(ha->ha_archive_id,
520                                            ha->ha_archive_cnt);
521                 OBD_FREE_PTR(ha);
522         }
523         up_write(&cdt->cdt_agent_lock);
524
525         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
526         rhashtable_free_and_destroy(&cdt->cdt_restore_hash, crh_free_hash,
527                                     cdt_mti);
528         rcu_barrier();
529 }
530
531 /*
532  * Coordinator state transition table, indexed on enum cdt_states, taking
533  * from and to states. For instance since CDT_INIT to CDT_RUNNING is a
534  * valid transition, cdt_transition[CDT_INIT][CDT_RUNNING] is true.
535  */
536 static bool cdt_transition[CDT_STATES_COUNT][CDT_STATES_COUNT] = {
537         /* from -> to:    stopped init   running disable stopping */
538         /* stopped */   { true,   true,  false,  false,  false },
539         /* init */      { true,   false, true,   false,  false },
540         /* running */   { false,  false, true,   true,   true },
541         /* disable */   { false,  false, true,   true,   true },
542         /* stopping */  { true,   false, false,  false,  false }
543 };
544
545 /**
546  * Change coordinator thread state
547  * Some combinations are not valid, so catch them here.
548  *
549  * Returns 0 on success, with old_state set if not NULL, or -EINVAL if
550  * the transition was not possible.
551  */
552 static int set_cdt_state_locked(struct coordinator *cdt,
553                                 enum cdt_states new_state)
554 {
555         int rc;
556         enum cdt_states state;
557
558         state = cdt->cdt_state;
559
560         if (cdt_transition[state][new_state]) {
561                 cdt->cdt_state = new_state;
562                 rc = 0;
563         } else {
564                 CDEBUG(D_HSM,
565                        "unexpected coordinator transition, from=%s, to=%s\n",
566                        cdt_mdt_state2str(state), cdt_mdt_state2str(new_state));
567                 rc = -EINVAL;
568         }
569
570         return rc;
571 }
572
573 static int set_cdt_state(struct coordinator *cdt, enum cdt_states new_state)
574 {
575         int rc;
576
577         mutex_lock(&cdt->cdt_state_lock);
578         rc = set_cdt_state_locked(cdt, new_state);
579         mutex_unlock(&cdt->cdt_state_lock);
580
581         return rc;
582 }
583
584 int cdt_getref_try(struct coordinator *cdt)
585 {
586         return refcount_inc_not_zero(&cdt->cdt_ref);
587 }
588
589 void cdt_putref(struct coordinator *cdt)
590 {
591         if (refcount_dec_and_test(&cdt->cdt_ref))
592                 wake_up(&cdt->cdt_waitq);
593 }
594
595 static int mdt_hsm_pending_restore(struct mdt_thread_info *mti);
596
597 static int cdt_start_pending_restore(struct mdt_device *mdt,
598                                      struct coordinator *cdt)
599 {
600         struct mdt_thread_info *cdt_mti;
601         unsigned int i = 0;
602         int rc;
603
604         /* wait until MDD initialize hsm actions llog */
605         while (!test_bit(MDT_FL_CFGLOG, &mdt->mdt_state) && i < obd_timeout) {
606                 schedule_timeout_interruptible(cfs_time_seconds(1));
607                 if (kthread_should_stop())
608                         return -ESHUTDOWN;
609                 i++;
610         }
611         if (!test_bit(MDT_FL_CFGLOG, &mdt->mdt_state))
612                 CWARN("%s: trying to init HSM before MDD\n", mdt_obd_name(mdt));
613
614         /* set up list of started restore requests */
615         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
616         rc = mdt_hsm_pending_restore(cdt_mti);
617         if (rc)
618                 CERROR("%s: cannot take the layout locks needed for registered restore: %d\n",
619                        mdt_obd_name(mdt), rc);
620
621         return rc;
622 }
623
624 /**
625  * coordinator thread
626  * \param data [IN] obd device
627  * \retval 0 success
628  * \retval -ve failure
629  */
630 static int mdt_coordinator(void *data)
631 {
632         struct mdt_thread_info  *mti = data;
633         struct mdt_device       *mdt = mti->mti_mdt;
634         struct coordinator      *cdt = &mdt->mdt_coordinator;
635         struct hsm_scan_data     hsd = { NULL };
636         time64_t                 last_housekeeping = 0;
637         size_t request_sz = 0;
638         int rc;
639         ENTRY;
640
641         CDEBUG(D_HSM, "%s: coordinator thread starting, pid=%d\n",
642                mdt_obd_name(mdt), current->pid);
643
644         hsd.hsd_mti = mti;
645         obd_uuid2fsname(hsd.hsd_fsname, mdt_obd_name(mdt),
646                         sizeof(hsd.hsd_fsname));
647
648         set_cdt_state(cdt, CDT_RUNNING);
649
650         /* Inform mdt_hsm_cdt_start(). */
651         wake_up(&cdt->cdt_waitq);
652
653         /* this initilazes cdt_last_cookie too */
654         rc = cdt_start_pending_restore(mdt, cdt);
655         if (rc < 0 || kthread_should_stop())
656                 GOTO(fail_to_start, rc);
657
658         refcount_set(&cdt->cdt_ref, 1);
659
660         while (1) {
661                 int i;
662                 int update_idx = 0;
663                 int updates_sz;
664                 int updates_cnt;
665                 u32 start_cat_idx;
666                 u32 start_rec_idx;
667                 struct hsm_record_update *updates;
668
669                 /* Limit execution of the expensive requests traversal
670                  * to at most one second. This prevents repeatedly
671                  * locking/unlocking the catalog for each request
672                  * and preventing other HSM operations from happening
673                  */
674                 wait_event_interruptible_timeout(cdt->cdt_waitq,
675                                                  kthread_should_stop() ||
676                                                  cdt->cdt_wakeup_coordinator,
677                                                  cfs_time_seconds(1));
678
679                 cdt->cdt_wakeup_coordinator = false;
680                 CDEBUG(D_HSM, "coordinator resumes\n");
681
682                 if (kthread_should_stop()) {
683                         CDEBUG(D_HSM, "Coordinator stops\n");
684
685                         /* Drop the running ref */
686                         cdt_putref(cdt);
687                         /* Wait threads to finish */
688                         wait_event(cdt->cdt_waitq,
689                                    refcount_read(&cdt->cdt_ref) == 0);
690                         rc = 0;
691                         break;
692                 }
693
694                 /* if coordinator is suspended continue to wait */
695                 if (cdt->cdt_state == CDT_DISABLE) {
696                         CDEBUG(D_HSM, "disable state, coordinator sleeps\n");
697                         continue;
698                 }
699
700                 /* If no event, and no housekeeping to do, continue to
701                  * wait. */
702                 if (last_housekeeping + cdt->cdt_loop_period <=
703                     ktime_get_real_seconds()) {
704                         last_housekeeping = ktime_get_real_seconds();
705                         hsd.hsd_housekeeping = true;
706                         start_cat_idx = 0;
707                         start_rec_idx = 0;
708                 } else if (cdt->cdt_event) {
709                         hsd.hsd_housekeeping = false;
710                         start_cat_idx = hsd.hsd_start_cat_idx;
711                         start_rec_idx = hsd.hsd_start_rec_idx;
712                 } else {
713                         continue;
714                 }
715
716                 cdt->cdt_event = false;
717
718                 CDEBUG(D_HSM, "coordinator starts reading llog\n");
719
720                 if (hsd.hsd_request_len != cdt->cdt_max_requests) {
721                         /* cdt_max_requests has changed,
722                          * we need to allocate a new buffer
723                          */
724                         struct hsm_scan_request *tmp = NULL;
725                         int max_requests = cdt->cdt_max_requests;
726                         OBD_ALLOC_LARGE(tmp, max_requests *
727                                         sizeof(struct hsm_scan_request));
728                         if (!tmp) {
729                                 CERROR("Failed to resize request buffer, "
730                                        "keeping it at %d\n",
731                                        hsd.hsd_request_len);
732                         } else {
733                                 if (hsd.hsd_request != NULL)
734                                         OBD_FREE_LARGE(hsd.hsd_request,
735                                                        request_sz);
736
737                                 hsd.hsd_request_len = max_requests;
738                                 request_sz = hsd.hsd_request_len *
739                                         sizeof(struct hsm_scan_request);
740                                 hsd.hsd_request = tmp;
741                         }
742                 }
743
744                 hsd.hsd_action_count = 0;
745                 hsd.hsd_request_count = 0;
746                 hsd.hsd_one_restore = false;
747
748                 rc = cdt_llog_process(mti->mti_env, mdt, mdt_coordinator_cb,
749                                       &hsd, start_cat_idx, start_rec_idx,
750                                       WRITE);
751                 if (rc < 0)
752                         goto clean_cb_alloc;
753
754                 CDEBUG(D_HSM, "found %d requests to send\n",
755                        hsd.hsd_request_count);
756
757                 if (list_empty(&cdt->cdt_agents)) {
758                         CDEBUG(D_HSM, "no agent available, "
759                                       "coordinator sleeps\n");
760                         /* reset HSM scanning index range. */
761                         hsd.hsd_start_cat_idx = start_cat_idx;
762                         hsd.hsd_start_rec_idx = start_rec_idx;
763                         goto clean_cb_alloc;
764                 }
765
766                 /* Compute how many HAI we have in all the requests */
767                 updates_cnt = 0;
768                 for (i = 0; i < hsd.hsd_request_count; i++) {
769                         const struct hsm_scan_request *request =
770                                 &hsd.hsd_request[i];
771
772                         updates_cnt += request->hal->hal_count;
773                 }
774
775                 /* Allocate a temporary array to store the cookies to
776                  * update, and their status. */
777                 updates_sz = updates_cnt * sizeof(*updates);
778                 OBD_ALLOC_LARGE(updates, updates_sz);
779                 if (updates == NULL) {
780                         CERROR("%s: Cannot allocate memory (%d bytes) "
781                                "for %d updates. Too many HSM requests?\n",
782                                mdt_obd_name(mdt), updates_sz, updates_cnt);
783                         goto clean_cb_alloc;
784                 }
785
786                 /* here hsd contains a list of requests to be started */
787                 for (i = 0; i < hsd.hsd_request_count; i++) {
788                         struct hsm_scan_request *request = &hsd.hsd_request[i];
789                         struct hsm_action_list  *hal = request->hal;
790                         struct hsm_action_item  *hai;
791                         int                      j;
792
793                         /* still room for work ? */
794                         if (atomic_read(&cdt->cdt_request_count) >=
795                             cdt->cdt_max_requests)
796                                 break;
797
798                         rc = mdt_hsm_agent_send(mti, hal, 0);
799                         /* if failure, we suppose it is temporary
800                          * if the copy tool failed to do the request
801                          * it has to use hsm_progress
802                          */
803
804                         /* set up cookie vector to set records status
805                          * after copy tools start or failed
806                          */
807                         hai = hai_first(hal);
808                         for (j = 0; j < hal->hal_count; j++) {
809                                 updates[update_idx].cookie = hai->hai_cookie;
810                                 updates[update_idx].status =
811                                         (rc ? ARS_WAITING : ARS_STARTED);
812                                 hai = hai_next(hai);
813                                 update_idx++;
814                         }
815
816                         /* TODO: narrow down the HSM action range that already
817                          * scanned accroding to the cookies when a failure
818                          * occurs.
819                          */
820                         if (rc) {
821                                 hsd.hsd_start_cat_idx = start_cat_idx;
822                                 hsd.hsd_start_rec_idx = start_rec_idx;
823                         }
824                 }
825
826                 if (update_idx) {
827                         rc = mdt_agent_record_update(mti, updates, update_idx);
828                         if (rc)
829                                 CERROR("%s: mdt_agent_record_update() failed, "
830                                        "rc=%d, cannot update records "
831                                        "for %d cookies\n",
832                                        mdt_obd_name(mdt), rc, update_idx);
833                 }
834
835                 OBD_FREE_LARGE(updates, updates_sz);
836
837 clean_cb_alloc:
838                 /* free hal allocated by callback */
839                 for (i = 0; i < hsd.hsd_request_count; i++) {
840                         struct hsm_scan_request *request = &hsd.hsd_request[i];
841
842                         OBD_FREE_LARGE(request->hal, request->hal_sz);
843                 }
844         }
845
846         if (hsd.hsd_request != NULL)
847                 OBD_FREE_LARGE(hsd.hsd_request, request_sz);
848
849 fail_to_start:
850         mdt_hsm_cdt_cleanup(mdt);
851
852         if (rc != 0)
853                 CERROR("%s: coordinator thread exiting, process=%d, rc=%d\n",
854                        mdt_obd_name(mdt), current->pid, rc);
855         else
856                 CDEBUG(D_HSM, "%s: coordinator thread exiting, process=%d,"
857                               " no error\n",
858                        mdt_obd_name(mdt), current->pid);
859
860         set_cdt_state(cdt, CDT_STOPPED);
861
862         /* Inform mdt_hsm_cdt_stop(). */
863         wake_up(&cdt->cdt_waitq);
864
865         RETURN(rc);
866 }
867
868 /**
869  * register a new HSM restore handle for a file and take EX lock on the layout
870  * \param mti [IN] thread info
871  * \param cdt [IN] coordinator
872  * \param fid [IN] fid of the file to restore
873  * \param he  [IN] HSM extent
874  * \retval 0 success
875  * \retval 1 restore handle already exists for the fid
876  * \retval -ve failure
877  */
878 int cdt_restore_handle_add(struct mdt_thread_info *mti, struct coordinator *cdt,
879                            const struct lu_fid *fid,
880                            const struct hsm_extent *he)
881 {
882         struct cdt_restore_handle *crh;
883         struct mdt_object *obj;
884         int rc;
885         ENTRY;
886
887         OBD_SLAB_ALLOC_PTR(crh, mdt_hsm_cdt_kmem);
888         if (crh == NULL)
889                 RETURN(-ENOMEM);
890
891         crh->crh_fid = *fid;
892         /* in V1 all file is restored
893          * crh->extent.start = he->offset;
894          * crh->extent.end = he->offset + he->length;
895          */
896         crh->crh_extent.start = 0;
897         crh->crh_extent.end = he->length;
898         atomic_set(&crh->crh_refc, 2);
899
900         rc = rhashtable_lookup_insert_fast(&cdt->cdt_restore_hash,
901                                            &crh->crh_hash, crh_hash_params);
902         if (rc) {
903                 OBD_SLAB_FREE_PTR(crh, mdt_hsm_cdt_kmem);
904                 RETURN(rc);
905         }
906
907         /* get the layout lock */
908         obj = mdt_object_find_lock(mti, &crh->crh_fid, &crh->crh_lh,
909                                    MDS_INODELOCK_LAYOUT, LCK_EX);
910         if (IS_ERR(obj)) {
911                 rc = rhashtable_remove_fast(&cdt->cdt_restore_hash,
912                                             &crh->crh_hash, crh_hash_params);
913                 /* rc < 0 means it has been removed in a parallel thread.
914                  * This shouldn't happen by design as at current stage record
915                  * hasn't been added in llog yet.
916                  */
917                 if (!rc)
918                         cdt_crh_put(crh, mti);
919                 cdt_crh_put(crh, mti);
920
921                 RETURN(PTR_ERR(obj));
922         }
923
924         /* We do not keep a reference on the object during the restore
925          * which can be very long.
926          */
927         mdt_object_put(mti->mti_env, obj);
928         cdt_crh_put(crh, mti);
929         RETURN(rc);
930 }
931
932 /**
933  * lookup a restore handle by FID
934  * \param cdt [IN] coordinator
935  * \param fid [IN] FID
936  * \retval true cdt_restore_handle found
937  * \retval false not found
938  */
939 bool cdt_restore_handle_exists(struct coordinator *cdt,
940                                const struct lu_fid *fid)
941 {
942         return rhashtable_lookup_fast(&cdt->cdt_restore_hash, fid,
943                                       crh_hash_params);
944 }
945
946 void cdt_restore_handle_del(struct mdt_thread_info *mti,
947                             struct coordinator *cdt, const struct lu_fid *fid)
948 {
949         struct cdt_restore_handle *crh;
950
951         /* give back layout lock */
952         rcu_read_lock();
953         crh = rhashtable_lookup(&cdt->cdt_restore_hash, fid, crh_hash_params);
954         if (crh &&
955             rhashtable_remove_fast(&cdt->cdt_restore_hash, &crh->crh_hash,
956                                    crh_hash_params))
957                 crh = NULL;
958         rcu_read_unlock();
959
960         /* crh has been removed in a parallel thread */
961         if (crh == NULL)
962                 return;
963
964         cdt_crh_put(crh, mti);
965 }
966
967 /**
968  * data passed to llog_cat_process() callback
969  * to scan requests and take actions
970  */
971 struct hsm_restore_data {
972         struct mdt_thread_info  *hrd_mti;
973 };
974
975 /**
976  *  llog_cat_process() callback, used to:
977  *  - find restore request and allocate the restore handle
978  * \param env [IN] environment
979  * \param llh [IN] llog handle
980  * \param hdr [IN] llog record
981  * \param data [IN/OUT] cb data = struct hsm_restore_data
982  * \retval 0 success
983  * \retval -ve failure
984  */
985 static int hsm_restore_cb(const struct lu_env *env,
986                           struct llog_handle *llh,
987                           struct llog_rec_hdr *hdr, void *data)
988 {
989         struct llog_agent_req_rec       *larr;
990         struct hsm_restore_data         *hrd;
991         struct hsm_action_item          *hai;
992         struct mdt_thread_info          *mti;
993         struct coordinator              *cdt;
994         int rc;
995         ENTRY;
996
997         hrd = data;
998         mti = hrd->hrd_mti;
999         cdt = &mti->mti_mdt->mdt_coordinator;
1000
1001         larr = (struct llog_agent_req_rec *)hdr;
1002         hai = &larr->arr_hai;
1003         if (hai->hai_cookie >= cdt->cdt_last_cookie) {
1004                 /* update the cookie to avoid collision */
1005                 cdt->cdt_last_cookie = hai->hai_cookie + 1;
1006         }
1007
1008         if (hai->hai_action != HSMA_RESTORE ||
1009             agent_req_in_final_state(larr->arr_status))
1010                 RETURN(0);
1011
1012         /* restore request not in a final state */
1013
1014         /* force replay of restore requests left in started state from previous
1015          * CDT context, to be canceled later if finally found to be incompatible
1016          * when being re-started */
1017         if (larr->arr_status == ARS_STARTED) {
1018                 larr->arr_status = ARS_WAITING;
1019                 larr->arr_req_change = ktime_get_real_seconds();
1020                 rc = llog_write(env, llh, hdr, hdr->lrh_index);
1021                 if (rc != 0)
1022                         GOTO(out, rc);
1023         }
1024
1025         rc = cdt_restore_handle_add(mti, cdt, &hai->hai_fid, &hai->hai_extent);
1026         if (rc == -EEXIST) {
1027                 CWARN("%s: duplicate restore record for fid="DFID" found in the llog: rc = %d\n",
1028                       mdt_obd_name(mti->mti_mdt), PFID(&hai->hai_fid), rc);
1029                 rc = 0;
1030         }
1031 out:
1032         RETURN(rc);
1033 }
1034
1035 /**
1036  * restore coordinator state at startup
1037  * the goal is to take a layout lock for each registered restore request
1038  * \param mti [IN] context
1039  */
1040 static int mdt_hsm_pending_restore(struct mdt_thread_info *mti)
1041 {
1042         struct hsm_restore_data  hrd;
1043         int                      rc;
1044         ENTRY;
1045
1046         hrd.hrd_mti = mti;
1047
1048         rc = cdt_llog_process(mti->mti_env, mti->mti_mdt, hsm_restore_cb, &hrd,
1049                               0, 0, WRITE);
1050
1051         RETURN(rc);
1052 }
1053
1054 int hsm_init_ucred(struct lu_ucred *uc)
1055 {
1056         ENTRY;
1057         uc->uc_valid = UCRED_OLD;
1058         uc->uc_o_uid = 0;
1059         uc->uc_o_gid = 0;
1060         uc->uc_o_fsuid = 0;
1061         uc->uc_o_fsgid = 0;
1062         uc->uc_uid = 0;
1063         uc->uc_gid = 0;
1064         uc->uc_fsuid = 0;
1065         uc->uc_fsgid = 0;
1066         uc->uc_suppgids[0] = -1;
1067         uc->uc_suppgids[1] = -1;
1068         uc->uc_cap = cap_combine(CAP_FS_SET, CAP_NFSD_SET);
1069         uc->uc_umask = 0777;
1070         uc->uc_ginfo = NULL;
1071         uc->uc_identity = NULL;
1072         /* always record internal HSM activity if also enabled globally */
1073         uc->uc_enable_audit = 1;
1074         /* do not let rbac interfere with HSM internal processing */
1075         uc->uc_rbac_file_perms = 1;
1076         uc->uc_rbac_dne_ops = 1;
1077         uc->uc_rbac_quota_ops = 1;
1078         uc->uc_rbac_byfid_ops = 1;
1079         uc->uc_rbac_chlg_ops = 1;
1080         uc->uc_rbac_fscrypt_admin = 1;
1081
1082         RETURN(0);
1083 }
1084
1085 /**
1086  * initialize coordinator struct
1087  * \param mdt [IN] device
1088  * \retval 0 success
1089  * \retval -ve failure
1090  */
1091 int mdt_hsm_cdt_init(struct mdt_device *mdt)
1092 {
1093         struct coordinator      *cdt = &mdt->mdt_coordinator;
1094         struct mdt_thread_info  *cdt_mti = NULL;
1095         int                      rc;
1096         ENTRY;
1097
1098         init_waitqueue_head(&cdt->cdt_waitq);
1099         init_rwsem(&cdt->cdt_llog_lock);
1100         init_rwsem(&cdt->cdt_agent_lock);
1101         init_rwsem(&cdt->cdt_request_lock);
1102         mutex_init(&cdt->cdt_state_lock);
1103         set_cdt_state(cdt, CDT_STOPPED);
1104
1105         INIT_LIST_HEAD(&cdt->cdt_request_list);
1106         INIT_LIST_HEAD(&cdt->cdt_agents);
1107
1108         cdt->cdt_request_cookie_hash = cfs_hash_create("REQUEST_COOKIE_HASH",
1109                                                        CFS_HASH_BITS_MIN,
1110                                                        CFS_HASH_BITS_MAX,
1111                                                        CFS_HASH_BKT_BITS,
1112                                                        0 /* extra bytes */,
1113                                                        CFS_HASH_MIN_THETA,
1114                                                        CFS_HASH_MAX_THETA,
1115                                                 &cdt_request_cookie_hash_ops,
1116                                                        CFS_HASH_DEFAULT);
1117         if (cdt->cdt_request_cookie_hash == NULL)
1118                 RETURN(-ENOMEM);
1119
1120         cdt->cdt_agent_record_hash = cfs_hash_create("AGENT_RECORD_HASH",
1121                                                      CFS_HASH_BITS_MIN,
1122                                                      CFS_HASH_BITS_MAX,
1123                                                      CFS_HASH_BKT_BITS,
1124                                                      0 /* extra bytes */,
1125                                                      CFS_HASH_MIN_THETA,
1126                                                      CFS_HASH_MAX_THETA,
1127                                                      &cdt_agent_record_hash_ops,
1128                                                      CFS_HASH_DEFAULT);
1129         if (cdt->cdt_agent_record_hash == NULL)
1130                 GOTO(out_request_cookie_hash, rc = -ENOMEM);
1131
1132         rc = lu_env_init(&cdt->cdt_env, LCT_MD_THREAD);
1133         if (rc < 0)
1134                 GOTO(out_agent_record_hash, rc);
1135
1136         /* for mdt_ucred(), lu_ucred stored in lu_ucred_key */
1137         rc = lu_context_init(&cdt->cdt_session, LCT_SERVER_SESSION);
1138         if (rc < 0)
1139                 GOTO(out_env, rc);
1140
1141         lu_context_enter(&cdt->cdt_session);
1142         cdt->cdt_env.le_ses = &cdt->cdt_session;
1143
1144         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
1145         LASSERT(cdt_mti != NULL);
1146
1147         cdt_mti->mti_env = &cdt->cdt_env;
1148         cdt_mti->mti_mdt = mdt;
1149
1150         hsm_init_ucred(mdt_ucred(cdt_mti));
1151
1152         /* default values for sysfs tunnables
1153          * can be override by MGS conf */
1154         cdt->cdt_default_archive_id = 1;
1155         cdt->cdt_grace_delay = 60;
1156         cdt->cdt_loop_period = 10;
1157         cdt->cdt_max_requests = 3;
1158         cdt->cdt_policy = CDT_DEFAULT_POLICY;
1159         cdt->cdt_active_req_timeout = 3600;
1160
1161         /* by default do not remove archives on last unlink */
1162         cdt->cdt_remove_archive_on_last_unlink = false;
1163
1164         RETURN(0);
1165
1166 out_env:
1167         lu_env_fini(&cdt->cdt_env);
1168 out_agent_record_hash:
1169         cfs_hash_putref(cdt->cdt_agent_record_hash);
1170         cdt->cdt_agent_record_hash = NULL;
1171 out_request_cookie_hash:
1172         cfs_hash_putref(cdt->cdt_request_cookie_hash);
1173         cdt->cdt_request_cookie_hash = NULL;
1174
1175         return rc;
1176 }
1177
1178 /**
1179  * free a coordinator thread
1180  * \param mdt [IN] device
1181  */
1182 int  mdt_hsm_cdt_fini(struct mdt_device *mdt)
1183 {
1184         struct coordinator *cdt = &mdt->mdt_coordinator;
1185         ENTRY;
1186
1187         lu_context_exit(cdt->cdt_env.le_ses);
1188         lu_context_fini(cdt->cdt_env.le_ses);
1189
1190         lu_env_fini(&cdt->cdt_env);
1191
1192         cfs_hash_putref(cdt->cdt_agent_record_hash);
1193         cdt->cdt_agent_record_hash = NULL;
1194
1195         cfs_hash_putref(cdt->cdt_request_cookie_hash);
1196         cdt->cdt_request_cookie_hash = NULL;
1197
1198         RETURN(0);
1199 }
1200
1201 /**
1202  * start a coordinator thread
1203  * \param mdt [IN] device
1204  * \retval 0 success
1205  * \retval -ve failure
1206  */
1207 static int mdt_hsm_cdt_start(struct mdt_device *mdt)
1208 {
1209         struct coordinator *cdt = &mdt->mdt_coordinator;
1210         struct mdt_thread_info *cdt_mti;
1211         int rc;
1212         void *ptr;
1213         struct task_struct *task;
1214         ENTRY;
1215
1216         /* functions defined but not yet used
1217          * this avoid compilation warning
1218          */
1219         ptr = dump_requests;
1220
1221         rc = set_cdt_state(cdt, CDT_INIT);
1222         if (rc) {
1223                 CERROR("%s: Coordinator already started or stopping\n",
1224                        mdt_obd_name(mdt));
1225                 RETURN(-EALREADY);
1226         }
1227
1228         BUILD_BUG_ON(BIT(CDT_POLICY_SHIFT_COUNT - 1) != CDT_POLICY_LAST);
1229         cdt->cdt_policy = CDT_DEFAULT_POLICY;
1230
1231         /* just need to be larger than previous one */
1232         /* cdt_last_cookie is protected by cdt_llog_lock */
1233         cdt->cdt_last_cookie = ktime_get_real_seconds();
1234         atomic_set(&cdt->cdt_request_count, 0);
1235         atomic_set(&cdt->cdt_archive_count, 0);
1236         atomic_set(&cdt->cdt_restore_count, 0);
1237         atomic_set(&cdt->cdt_remove_count, 0);
1238         cdt->cdt_user_request_mask = (1UL << HSMA_RESTORE);
1239         cdt->cdt_group_request_mask = (1UL << HSMA_RESTORE);
1240         cdt->cdt_other_request_mask = (1UL << HSMA_RESTORE);
1241         rc = rhashtable_init(&cdt->cdt_restore_hash, &crh_hash_params);
1242         if (rc) {
1243                 CERROR("%s: failed to create cdt_restore hash: rc = %d\n",
1244                        mdt_obd_name(mdt), rc);
1245                 set_cdt_state(cdt, CDT_STOPPED);
1246                 RETURN(rc);
1247         }
1248
1249         /* to avoid deadlock when start is made through sysfs
1250          * sysfs entries are created by the coordinator thread
1251          */
1252         if (mdt->mdt_bottom->dd_rdonly)
1253                 RETURN(0);
1254
1255         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
1256         task = kthread_run(mdt_coordinator, cdt_mti, "hsm_cdtr");
1257         if (IS_ERR(task)) {
1258                 rc = PTR_ERR(task);
1259                 set_cdt_state(cdt, CDT_STOPPED);
1260                 CERROR("%s: error starting coordinator thread: %d\n",
1261                        mdt_obd_name(mdt), rc);
1262         } else {
1263                 cdt->cdt_task = task;
1264                 wait_event(cdt->cdt_waitq,
1265                            cdt->cdt_state != CDT_INIT);
1266                 CDEBUG(D_HSM, "%s: coordinator thread started\n",
1267                        mdt_obd_name(mdt));
1268                 rc = 0;
1269         }
1270
1271         RETURN(rc);
1272 }
1273
1274 /**
1275  * stop a coordinator thread
1276  * \param mdt [IN] device
1277  */
1278 int mdt_hsm_cdt_stop(struct mdt_device *mdt)
1279 {
1280         struct coordinator *cdt = &mdt->mdt_coordinator;
1281         int rc;
1282
1283         ENTRY;
1284
1285         /* stop coordinator thread */
1286         rc = set_cdt_state(cdt, CDT_STOPPING);
1287         if (rc)
1288                 RETURN(rc);
1289
1290         kthread_stop(cdt->cdt_task);
1291         rc = wait_event_interruptible(cdt->cdt_waitq,
1292                                       cdt->cdt_state == CDT_STOPPED);
1293         if (rc)
1294                 RETURN(-EINTR);
1295
1296         cdt->cdt_task = NULL;
1297         RETURN(0);
1298 }
1299
1300 static int mdt_hsm_set_exists(struct mdt_thread_info *mti,
1301                               const struct lu_fid *fid,
1302                               u32 archive_id)
1303 {
1304         struct mdt_object *obj;
1305         struct md_hsm mh;
1306         int rc;
1307
1308         obj = mdt_hsm_get_md_hsm(mti, fid, &mh);
1309         if (IS_ERR(obj))
1310                 GOTO(out, rc = PTR_ERR(obj));
1311
1312         if (mh.mh_flags & HS_EXISTS &&
1313             mh.mh_arch_id == archive_id)
1314                 GOTO(out_obj, rc = 0);
1315
1316         mh.mh_flags |= HS_EXISTS;
1317         mh.mh_arch_id = archive_id;
1318         rc = mdt_hsm_attr_set(mti, obj, &mh);
1319
1320 out_obj:
1321         mdt_object_put(mti->mti_env, obj);
1322 out:
1323         return rc;
1324 }
1325
1326 /**
1327  * register all requests from an hal in the memory list
1328  * \param mti [IN] context
1329  * \param hal [IN] request
1330  * \param uuid [OUT] in case of CANCEL, the uuid of the agent
1331  *  which is running the CT
1332  * \retval 0 success
1333  * \retval -ve failure
1334  */
1335 int mdt_hsm_add_hal(struct mdt_thread_info *mti,
1336                     struct hsm_action_list *hal, struct obd_uuid *uuid)
1337 {
1338         struct mdt_device       *mdt = mti->mti_mdt;
1339         struct coordinator      *cdt = &mdt->mdt_coordinator;
1340         struct hsm_action_item  *hai;
1341         int                      rc = 0, i;
1342         ENTRY;
1343
1344         /* register request in memory list */
1345         hai = hai_first(hal);
1346         for (i = 0; i < hal->hal_count; i++, hai = hai_next(hai)) {
1347                 struct cdt_agent_req *car;
1348
1349                 /* in case of a cancel request, we first mark the ondisk
1350                  * record of the request we want to stop as canceled
1351                  * this does not change the cancel record
1352                  * it will be done when updating the request status
1353                  */
1354                 if (hai->hai_action == HSMA_CANCEL) {
1355                         struct hsm_record_update update = {
1356                                 .cookie = hai->hai_cookie,
1357                                 .status = ARS_CANCELED,
1358                         };
1359
1360                         rc = mdt_agent_record_update(mti, &update, 1);
1361                         if (rc) {
1362                                 CERROR("%s: mdt_agent_record_update() failed, "
1363                                        "rc=%d, cannot update status to %s "
1364                                        "for cookie %#llx\n",
1365                                        mdt_obd_name(mdt), rc,
1366                                        agent_req_status2name(ARS_CANCELED),
1367                                        hai->hai_cookie);
1368                                 GOTO(out, rc);
1369                         }
1370
1371                         /* find the running request to set it canceled */
1372                         car = mdt_cdt_find_request(cdt, hai->hai_cookie);
1373                         if (car != NULL) {
1374                                 car->car_canceled = 1;
1375                                 /* uuid has to be changed to the one running the
1376                                 * request to cancel */
1377                                 *uuid = car->car_uuid;
1378                                 mdt_cdt_put_request(car);
1379                         }
1380                         /* no need to memorize cancel request
1381                          * this also avoid a deadlock when we receive
1382                          * a purge all requests command
1383                          */
1384                         continue;
1385                 }
1386
1387                 if (hai->hai_action == HSMA_ARCHIVE) {
1388                         rc = mdt_hsm_set_exists(mti, &hai->hai_fid,
1389                                                 hal->hal_archive_id);
1390                         if (rc == -ENOENT)
1391                                 continue;
1392                         else if (rc < 0)
1393                                 GOTO(out, rc);
1394                 }
1395
1396                 car = mdt_cdt_alloc_request(hal->hal_archive_id, hal->hal_flags,
1397                                             uuid, hai);
1398                 if (IS_ERR(car))
1399                         GOTO(out, rc = PTR_ERR(car));
1400
1401                 rc = mdt_cdt_add_request(cdt, car);
1402                 if (rc != 0)
1403                         mdt_cdt_free_request(car);
1404         }
1405 out:
1406         RETURN(rc);
1407 }
1408
1409 /**
1410  * swap layouts between 2 fids
1411  * \param mti [IN] context
1412  * \param obj [IN]
1413  * \param dfid [IN]
1414  * \param mh_common [IN] MD HSM
1415  */
1416 static int hsm_swap_layouts(struct mdt_thread_info *mti,
1417                             struct mdt_object *obj, const struct lu_fid *dfid,
1418                             struct md_hsm *mh_common)
1419 {
1420         struct mdt_object       *dobj;
1421         struct mdt_lock_handle  *dlh;
1422         int                      rc;
1423         ENTRY;
1424
1425         if (!mdt_object_exists(obj))
1426                 GOTO(out, rc = -ENOENT);
1427
1428         /* we already have layout lock on obj so take only
1429          * on dfid */
1430         dlh = &mti->mti_lh[MDT_LH_OLD];
1431         dobj = mdt_object_find_lock(mti, dfid, dlh, MDS_INODELOCK_LAYOUT,
1432                                     LCK_EX);
1433         if (IS_ERR(dobj))
1434                 GOTO(out, rc = PTR_ERR(dobj));
1435
1436         /* if copy tool closes the volatile before sending the final
1437          * progress through llapi_hsm_copy_end(), all the objects
1438          * are removed and mdd_swap_layout LBUG */
1439         if (!mdt_object_exists(dobj)) {
1440                 CERROR("%s: Copytool has closed volatile file "DFID"\n",
1441                        mdt_obd_name(mti->mti_mdt), PFID(dfid));
1442                 GOTO(out_dobj, rc = -ENOENT);
1443         }
1444         /* Since we only handle restores here, unconditionally use
1445          * SWAP_LAYOUTS_MDS_HSM flag to ensure original layout will
1446          * be preserved in case of failure during swap_layout and not
1447          * leave a file in an intermediate but incoherent state.
1448          * But need to setup HSM xattr of data FID before, reuse
1449          * mti and mh presets for FID in hsm_cdt_request_completed(),
1450          * only need to clear RELEASED and DIRTY.
1451          */
1452         mh_common->mh_flags &= ~(HS_RELEASED | HS_DIRTY);
1453         rc = mdt_hsm_attr_set(mti, dobj, mh_common);
1454         if (rc)
1455                 GOTO(out_dobj, rc);
1456
1457         rc = mo_swap_layouts(mti->mti_env, mdt_object_child(obj),
1458                              mdt_object_child(dobj), 0, 0, 0);
1459         if (rc)
1460                 GOTO(out_dobj, rc);
1461
1462         rc = mdt_lsom_downgrade(mti, obj);
1463         if (rc)
1464                 CDEBUG(D_INODE,
1465                        "%s: File fid="DFID" SOM downgrade failed, rc = %d\n",
1466                        mdt_obd_name(mti->mti_mdt),
1467                        PFID(mdt_object_fid(obj)), rc);
1468 out_dobj:
1469         mdt_object_unlock_put(mti, dobj, dlh, 1);
1470 out:
1471         RETURN(rc);
1472 }
1473
1474 /**
1475  * update status of a completed request
1476  * \param mti [IN] context
1477  * \param pgs [IN] progress of the copy tool
1478  * \retval 0 success
1479  * \retval -ve failure
1480  */
1481 static int hsm_cdt_request_completed(struct mdt_thread_info *mti,
1482                                      struct hsm_progress_kernel *pgs,
1483                                      const struct cdt_agent_req *car,
1484                                      enum agent_req_status *status)
1485 {
1486         const struct lu_env *env = mti->mti_env;
1487         struct mdt_device *mdt = mti->mti_mdt;
1488         struct coordinator *cdt = &mdt->mdt_coordinator;
1489         struct mdt_object *obj = NULL;
1490         enum changelog_rec_flags clf_flags = 0;
1491         struct md_hsm mh;
1492         bool is_mh_changed;
1493         bool need_changelog = true;
1494         int rc = 0;
1495
1496         ENTRY;
1497         /* default is to retry */
1498         *status = ARS_WAITING;
1499
1500         /* find object by FID, mdt_hsm_get_md_hsm() returns obj or err
1501          * if error/removed continue anyway to get correct reporting done */
1502         obj = mdt_hsm_get_md_hsm(mti, &car->car_hai->hai_fid, &mh);
1503         /* we will update MD HSM only if needed */
1504         is_mh_changed = false;
1505
1506         /* no need to change mh->mh_arch_id
1507          * mdt_hsm_get_md_hsm() got it from disk and it is still valid
1508          */
1509         if (pgs->hpk_errval != 0) {
1510                 switch (pgs->hpk_errval) {
1511                 case ENOSYS:
1512                         /* the copy tool does not support cancel
1513                          * so the cancel request is failed
1514                          * As we cannot distinguish a cancel progress
1515                          * from another action progress (they have the
1516                          * same cookie), we suppose here the CT returns
1517                          * ENOSYS only if does not support cancel
1518                          */
1519                         /* this can also happen when cdt calls it to
1520                          * for a timed out request */
1521                         *status = ARS_FAILED;
1522                         /* to have a cancel event in changelog */
1523                         pgs->hpk_errval = ECANCELED;
1524                         break;
1525                 case ECANCELED:
1526                         /* the request record has already been set to
1527                          * ARS_CANCELED, this set the cancel request
1528                          * to ARS_SUCCEED */
1529                         *status = ARS_SUCCEED;
1530                         break;
1531                 default:
1532                         /* retry only if current policy or requested, and
1533                          * object is not on error/removed */
1534                         *status = (cdt->cdt_policy & CDT_NORETRY_ACTION ||
1535                                    !(pgs->hpk_flags & HP_FLAG_RETRY) ||
1536                                    IS_ERR(obj)) ? ARS_FAILED : ARS_WAITING;
1537                         break;
1538                 }
1539
1540                 rc = hsm_set_cl_error(&clf_flags, pgs->hpk_errval);
1541                 if (rc == -EOVERFLOW) {
1542                         CERROR("%s: Request %#llx on "DFID" failed, error code %d too large\n",
1543                                mdt_obd_name(mdt), pgs->hpk_cookie,
1544                                PFID(&pgs->hpk_fid), (int)abs(pgs->hpk_errval));
1545                         rc = 0;
1546                 }
1547
1548                 switch (car->car_hai->hai_action) {
1549                 case HSMA_ARCHIVE:
1550                         hsm_set_cl_event(&clf_flags, HE_ARCHIVE);
1551                         break;
1552                 case HSMA_RESTORE:
1553                         hsm_set_cl_event(&clf_flags, HE_RESTORE);
1554                         break;
1555                 case HSMA_REMOVE:
1556                         hsm_set_cl_event(&clf_flags, HE_REMOVE);
1557                         break;
1558                 case HSMA_CANCEL:
1559                         hsm_set_cl_event(&clf_flags, HE_CANCEL);
1560                         CERROR("%s: Failed request %#llx on "DFID
1561                                " cannot be a CANCEL\n",
1562                                mdt_obd_name(mdt),
1563                                pgs->hpk_cookie,
1564                                PFID(&pgs->hpk_fid));
1565                         break;
1566                 default:
1567                         CERROR("%s: Failed request %#llx on "DFID
1568                                " %d is an unknown action\n",
1569                                mdt_obd_name(mdt),
1570                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1571                                car->car_hai->hai_action);
1572                         rc = -EINVAL;
1573                         break;
1574                 }
1575         } else {
1576                 *status = ARS_SUCCEED;
1577                 switch (car->car_hai->hai_action) {
1578                 case HSMA_ARCHIVE:
1579                         hsm_set_cl_event(&clf_flags, HE_ARCHIVE);
1580                         /* set ARCHIVE keep EXIST and clear LOST and
1581                          * DIRTY */
1582                         mh.mh_arch_ver = pgs->hpk_data_version;
1583                         mh.mh_flags |= HS_ARCHIVED;
1584                         mh.mh_flags &= ~(HS_LOST|HS_DIRTY);
1585                         is_mh_changed = true;
1586                         break;
1587                 case HSMA_RESTORE:
1588                         hsm_set_cl_event(&clf_flags, HE_RESTORE);
1589
1590                         /* do not clear RELEASED and DIRTY here
1591                          * this will occur in hsm_swap_layouts()
1592                          */
1593
1594                         /* Restoring has changed the file version on
1595                          * disk. */
1596                         mh.mh_arch_ver = pgs->hpk_data_version;
1597                         is_mh_changed = true;
1598                         break;
1599                 case HSMA_REMOVE:
1600                         hsm_set_cl_event(&clf_flags, HE_REMOVE);
1601                         /* clear ARCHIVED EXISTS and LOST */
1602                         mh.mh_flags &= ~(HS_ARCHIVED | HS_EXISTS | HS_LOST);
1603                         is_mh_changed = true;
1604                         break;
1605                 case HSMA_CANCEL:
1606                         hsm_set_cl_event(&clf_flags, HE_CANCEL);
1607                         CERROR("%s: Successful request %#llx on "DFID" cannot be a CANCEL\n",
1608                                mdt_obd_name(mdt),
1609                                pgs->hpk_cookie,
1610                                PFID(&pgs->hpk_fid));
1611                         break;
1612                 default:
1613                         CERROR("%s: Successful request %#llx on "DFID" %d is an unknown action\n",
1614                                mdt_obd_name(mdt),
1615                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1616                                car->car_hai->hai_action);
1617                         rc = -EINVAL;
1618                         break;
1619                 }
1620         }
1621
1622         /* rc != 0 means error when analysing action, it may come from
1623          * a crasy CT no need to manage DIRTY
1624          * and if mdt_hsm_get_md_hsm() has returned an error, mh has not been
1625          * filled
1626          */
1627         if (rc == 0 && !IS_ERR(obj))
1628                 hsm_set_cl_flags(&clf_flags,
1629                                  mh.mh_flags & HS_DIRTY ? CLF_HSM_DIRTY : 0);
1630
1631         /* unlock is done later, after layout lock management */
1632         if (is_mh_changed && !IS_ERR(obj))
1633                 rc = mdt_hsm_attr_set(mti, obj, &mh);
1634
1635         /* we give back layout lock only if restore was successful or
1636          * if no retry will be attempted and if object is still alive,
1637          * in other cases we just unlock the object */
1638         if (car->car_hai->hai_action == HSMA_RESTORE) {
1639                 struct mdt_lock_handle *lh;
1640
1641                 /* restore in data FID done, we swap the layouts
1642                  * only if restore is successful */
1643                 if (pgs->hpk_errval == 0 && !IS_ERR(obj)) {
1644                         rc = hsm_swap_layouts(mti, obj, &car->car_hai->hai_dfid,
1645                                               &mh);
1646                         if (rc) {
1647                                 if (cdt->cdt_policy & CDT_NORETRY_ACTION)
1648                                         *status = ARS_FAILED;
1649                                 pgs->hpk_errval = -rc;
1650                                 hsm_set_cl_error(&clf_flags, pgs->hpk_errval);
1651                         }
1652                 }
1653                 /* we have to retry, so keep layout lock */
1654                 if (*status == ARS_WAITING)
1655                         GOTO(out, rc);
1656
1657                 /* restore special case, need to create ChangeLog record
1658                  * before to give back layout lock to avoid concurrent
1659                  * file updater to post out of order ChangeLog */
1660                 mo_changelog(env, CL_HSM, clf_flags, mdt->mdt_child,
1661                              &car->car_hai->hai_fid);
1662                 need_changelog = false;
1663
1664                 cdt_restore_handle_del(mti, cdt, &car->car_hai->hai_fid);
1665                 if (!IS_ERR_OR_NULL(obj)) {
1666                         /* flush UPDATE lock so attributes are upadated */
1667                         lh = &mti->mti_lh[MDT_LH_OLD];
1668                         mdt_object_lock(mti, obj, lh, MDS_INODELOCK_UPDATE,
1669                                         LCK_EX);
1670                         mdt_object_unlock(mti, obj, lh, 1);
1671                 }
1672         }
1673
1674         GOTO(out, rc);
1675
1676 out:
1677         /* always add a ChangeLog record */
1678         if (need_changelog)
1679                 mo_changelog(env, CL_HSM, clf_flags, mdt->mdt_child,
1680                              &car->car_hai->hai_fid);
1681
1682         if (!IS_ERR(obj))
1683                 mdt_object_put(mti->mti_env, obj);
1684
1685         RETURN(rc);
1686 }
1687
1688 /**
1689  * update status of a request
1690  * \param mti [IN] context
1691  * \param pgs [IN] progress of the copy tool
1692  * \retval 0 success
1693  * \retval -ve failure
1694  */
1695 int mdt_hsm_update_request_state(struct mdt_thread_info *mti,
1696                                  struct hsm_progress_kernel *pgs)
1697 {
1698         struct mdt_device       *mdt = mti->mti_mdt;
1699         struct coordinator      *cdt = &mdt->mdt_coordinator;
1700         struct cdt_agent_req    *car;
1701         int                      rc = 0;
1702         ENTRY;
1703
1704         /* no coordinator started, so we cannot serve requests */
1705         if (!cdt_getref_try(cdt))
1706                 RETURN(-EAGAIN);
1707
1708         /* first do sanity checks */
1709         car = mdt_cdt_update_request(cdt, pgs);
1710         if (IS_ERR(car)) {
1711                 CERROR("%s: Cannot find running request for cookie %#llx"
1712                        " on fid="DFID"\n",
1713                        mdt_obd_name(mdt),
1714                        pgs->hpk_cookie, PFID(&pgs->hpk_fid));
1715
1716                 GOTO(putref, rc = PTR_ERR(car));
1717         }
1718
1719         CDEBUG(D_HSM, "Progress received for fid="DFID" cookie=%#llx"
1720                       " action=%s flags=%d err=%d fid="DFID" dfid="DFID"\n",
1721                       PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1722                       hsm_copytool_action2name(car->car_hai->hai_action),
1723                       pgs->hpk_flags, pgs->hpk_errval,
1724                       PFID(&car->car_hai->hai_fid),
1725                       PFID(&car->car_hai->hai_dfid));
1726
1727         /* progress is done on FID or data FID depending of the action and
1728          * of the copy progress */
1729         /* for restore progress is used to send back the data FID to cdt */
1730         if (car->car_hai->hai_action == HSMA_RESTORE &&
1731             lu_fid_eq(&car->car_hai->hai_fid, &car->car_hai->hai_dfid))
1732                 car->car_hai->hai_dfid = pgs->hpk_fid;
1733
1734         if ((car->car_hai->hai_action == HSMA_RESTORE ||
1735              car->car_hai->hai_action == HSMA_ARCHIVE) &&
1736             (!lu_fid_eq(&pgs->hpk_fid, &car->car_hai->hai_dfid) &&
1737              !lu_fid_eq(&pgs->hpk_fid, &car->car_hai->hai_fid))) {
1738                 CERROR("%s: Progress on "DFID" for cookie %#llx"
1739                        " does not match request FID "DFID" nor data FID "
1740                        DFID"\n",
1741                        mdt_obd_name(mdt),
1742                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1743                        PFID(&car->car_hai->hai_fid),
1744                        PFID(&car->car_hai->hai_dfid));
1745                 GOTO(out, rc = -EINVAL);
1746         }
1747
1748         if (pgs->hpk_errval != 0 && !(pgs->hpk_flags & HP_FLAG_COMPLETED)) {
1749                 CERROR("%s: Progress on "DFID" for cookie %#llx action=%s"
1750                        " is not coherent (err=%d and not completed"
1751                        " (flags=%d))\n",
1752                        mdt_obd_name(mdt),
1753                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1754                        hsm_copytool_action2name(car->car_hai->hai_action),
1755                        pgs->hpk_errval, pgs->hpk_flags);
1756                 GOTO(out, rc = -EINVAL);
1757         }
1758
1759         /* now progress is valid */
1760
1761         /* we use a root like ucred */
1762         hsm_init_ucred(mdt_ucred(mti));
1763
1764         if (pgs->hpk_flags & HP_FLAG_COMPLETED) {
1765                 enum agent_req_status status;
1766                 struct hsm_record_update update;
1767                 int rc1;
1768
1769                 rc = hsm_cdt_request_completed(mti, pgs, car, &status);
1770
1771                 CDEBUG(D_HSM, "updating record: fid="DFID" cookie=%#llx action=%s "
1772                               "status=%s\n",
1773                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1774                        hsm_copytool_action2name(car->car_hai->hai_action),
1775                        agent_req_status2name(status));
1776
1777                 /* update record first (LU-9075) */
1778                 update.cookie = pgs->hpk_cookie;
1779                 update.status = status;
1780
1781                 rc1 = mdt_agent_record_update(mti, &update, 1);
1782                 if (rc1)
1783                         CERROR("%s: mdt_agent_record_update() failed,"
1784                                " rc=%d, cannot update status to %s"
1785                                " for cookie %#llx\n",
1786                                mdt_obd_name(mdt), rc1,
1787                                agent_req_status2name(status),
1788                                pgs->hpk_cookie);
1789                 rc = (rc != 0 ? rc : rc1);
1790
1791                 /* then remove request from memory list (LU-9075) */
1792                 mdt_cdt_remove_request(cdt, pgs->hpk_cookie);
1793
1794                 /* ct has completed a request, so a slot is available,
1795                  * signal the coordinator to find new work */
1796                 mdt_hsm_cdt_event(cdt);
1797         } else {
1798                 /* if copytool send a progress on a canceled request
1799                  * we inform copytool it should stop
1800                  */
1801                 if (car->car_canceled == 1)
1802                         rc = -ECANCELED;
1803         }
1804         GOTO(out, rc);
1805
1806 out:
1807         /* remove ref got from mdt_cdt_update_request() */
1808         mdt_cdt_put_request(car);
1809
1810 putref:
1811         cdt_putref(cdt);
1812         return rc;
1813 }
1814
1815
1816 /**
1817  *  llog_cat_process() callback, used to:
1818  *  - purge all requests
1819  * \param env [IN] environment
1820  * \param llh [IN] llog handle
1821  * \param hdr [IN] llog record
1822  * \param data [IN] cb data = struct mdt_thread_info
1823  * \retval 0 success
1824  * \retval -ve failure
1825  */
1826 static int mdt_cancel_all_cb(const struct lu_env *env,
1827                              struct llog_handle *llh,
1828                              struct llog_rec_hdr *hdr, void *data)
1829 {
1830         struct llog_agent_req_rec *larr = (struct llog_agent_req_rec *)hdr;
1831         struct hsm_action_item *hai = &larr->arr_hai;
1832         struct mdt_thread_info  *mti = data;
1833         struct coordinator *cdt = &mti->mti_mdt->mdt_coordinator;
1834         int rc;
1835         ENTRY;
1836
1837         if (larr->arr_status != ARS_WAITING &&
1838             larr->arr_status != ARS_STARTED)
1839                 RETURN(0);
1840
1841         /* Unlock the EX layout lock */
1842         if (hai->hai_action == HSMA_RESTORE)
1843                 cdt_restore_handle_del(mti, cdt, &hai->hai_fid);
1844
1845         larr->arr_status = ARS_CANCELED;
1846         larr->arr_req_change = ktime_get_real_seconds();
1847         rc = llog_write(env, llh, hdr, hdr->lrh_index);
1848         if (rc < 0) {
1849                 CERROR("%s: cannot update agent log: rc = %d\n",
1850                        mdt_obd_name(mti->mti_mdt), rc);
1851                 rc = LLOG_DEL_RECORD;
1852         }
1853
1854         RETURN(rc);
1855 }
1856
1857 /**
1858  * cancel all actions
1859  * \param obd [IN] MDT device
1860  */
1861 static int hsm_cancel_all_actions(struct mdt_device *mdt)
1862 {
1863         struct lu_env                    env;
1864         struct lu_context                session;
1865         struct mdt_thread_info          *mti;
1866         struct coordinator              *cdt = &mdt->mdt_coordinator;
1867         struct cdt_agent_req            *car;
1868         struct hsm_action_list          *hal = NULL;
1869         struct hsm_action_item          *hai;
1870         int                              hal_sz = 0, hal_len, rc;
1871         enum cdt_states                  old_state;
1872         ENTRY;
1873
1874         rc = lu_env_init(&env, LCT_MD_THREAD);
1875         if (rc < 0)
1876                 RETURN(rc);
1877
1878         /* for mdt_ucred(), lu_ucred stored in lu_ucred_key */
1879         rc = lu_context_init(&session, LCT_SERVER_SESSION);
1880         if (rc < 0)
1881                 GOTO(out_env, rc);
1882
1883         lu_context_enter(&session);
1884         env.le_ses = &session;
1885
1886         mti = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
1887         LASSERT(mti != NULL);
1888
1889         mti->mti_env = &env;
1890         mti->mti_mdt = mdt;
1891
1892         hsm_init_ucred(mdt_ucred(mti));
1893
1894         mutex_lock(&cdt->cdt_state_lock);
1895         old_state = cdt->cdt_state;
1896
1897         /* disable coordinator */
1898         rc = set_cdt_state_locked(cdt, CDT_DISABLE);
1899         if (rc)
1900                 GOTO(out_cdt_state_unlock, rc);
1901
1902         /* send cancel to all running requests */
1903         down_read(&cdt->cdt_request_lock);
1904         list_for_each_entry(car, &cdt->cdt_request_list, car_request_list) {
1905                 mdt_cdt_get_request(car);
1906                 /* request is not yet removed from list, it will be done
1907                  * when copytool will return progress
1908                  */
1909
1910                 if (car->car_hai->hai_action == HSMA_CANCEL) {
1911                         mdt_cdt_put_request(car);
1912                         continue;
1913                 }
1914
1915                 /* needed size */
1916                 hal_len = sizeof(*hal) + round_up(MTI_NAME_MAXLEN + 1, 8) +
1917                           round_up(car->car_hai->hai_len, 8);
1918
1919                 if (hal_len > hal_sz && hal_sz > 0) {
1920                         /* not enough room, free old buffer */
1921                         OBD_FREE(hal, hal_sz);
1922                         hal = NULL;
1923                 }
1924
1925                 /* empty buffer, allocate one */
1926                 if (hal == NULL) {
1927                         hal_sz = hal_len;
1928                         OBD_ALLOC(hal, hal_sz);
1929                         if (hal == NULL) {
1930                                 mdt_cdt_put_request(car);
1931                                 up_read(&cdt->cdt_request_lock);
1932                                 GOTO(out_cdt_state, rc = -ENOMEM);
1933                         }
1934                 }
1935
1936                 hal->hal_version = HAL_VERSION;
1937                 obd_uuid2fsname(hal->hal_fsname, mdt_obd_name(mdt),
1938                                 MTI_NAME_MAXLEN);
1939                 hal->hal_fsname[MTI_NAME_MAXLEN] = '\0';
1940                 hal->hal_archive_id = car->car_archive_id;
1941                 hal->hal_flags = car->car_flags;
1942                 hal->hal_count = 0;
1943
1944                 hai = hai_first(hal);
1945                 memcpy(hai, car->car_hai, car->car_hai->hai_len);
1946                 hai->hai_action = HSMA_CANCEL;
1947                 hal->hal_count = 1;
1948
1949                 /* it is possible to safely call mdt_hsm_agent_send()
1950                  * (ie without a deadlock on cdt_request_lock), because the
1951                  * write lock is taken only if we are not in purge mode
1952                  * (mdt_hsm_agent_send() does not call mdt_cdt_add_request()
1953                  *   nor mdt_cdt_remove_request())
1954                  */
1955                 /* no conflict with cdt thread because cdt is disable and we
1956                  * have the request lock */
1957                 mdt_hsm_agent_send(mti, hal, 1);
1958
1959                 mdt_cdt_put_request(car);
1960         }
1961         up_read(&cdt->cdt_request_lock);
1962
1963         if (hal != NULL)
1964                 OBD_FREE(hal, hal_sz);
1965
1966         /* cancel all on-disk records */
1967         rc = cdt_llog_process(mti->mti_env, mti->mti_mdt, mdt_cancel_all_cb,
1968                               (void *)mti, 0, 0, WRITE);
1969 out_cdt_state:
1970         /* Enable coordinator, unless the coordinator was stopping. */
1971         set_cdt_state_locked(cdt, old_state);
1972 out_cdt_state_unlock:
1973         mutex_unlock(&cdt->cdt_state_lock);
1974
1975         lu_context_exit(&session);
1976         lu_context_fini(&session);
1977 out_env:
1978         lu_env_fini(&env);
1979
1980         RETURN(rc);
1981 }
1982
1983 /**
1984  * check if a request is compatible with file status
1985  * \param hai [IN] request description
1986  * \param archive_id [IN] request archive id
1987  * \param rq_flags [IN] request flags
1988  * \param hsm [IN] file HSM metadata
1989  * \retval boolean
1990  */
1991 bool mdt_hsm_is_action_compat(const struct hsm_action_item *hai,
1992                               u32 archive_id, u64 rq_flags,
1993                               const struct md_hsm *hsm)
1994 {
1995         int      is_compat = false;
1996         int      hsm_flags;
1997         ENTRY;
1998
1999         hsm_flags = hsm->mh_flags;
2000         switch (hai->hai_action) {
2001         case HSMA_ARCHIVE:
2002                 if (!(hsm_flags & HS_NOARCHIVE) &&
2003                     (hsm_flags & HS_DIRTY || !(hsm_flags & HS_ARCHIVED)))
2004                         is_compat = true;
2005
2006                 if (hsm_flags & HS_EXISTS &&
2007                     archive_id != 0 &&
2008                     archive_id != hsm->mh_arch_id)
2009                         is_compat = false;
2010
2011                 break;
2012         case HSMA_RESTORE:
2013                 if (!(hsm_flags & HS_DIRTY) && (hsm_flags & HS_RELEASED) &&
2014                     hsm_flags & HS_ARCHIVED && !(hsm_flags & HS_LOST))
2015                         is_compat = true;
2016                 break;
2017         case HSMA_REMOVE:
2018                 if (!(hsm_flags & HS_RELEASED) &&
2019                     (hsm_flags & (HS_ARCHIVED | HS_EXISTS)))
2020                         is_compat = true;
2021                 break;
2022         case HSMA_CANCEL:
2023                 is_compat = true;
2024                 break;
2025         }
2026         CDEBUG(D_HSM, "fid="DFID" action=%s flags=%#llx"
2027                       " extent=%#llx-%#llx hsm_flags=%.8X %s\n",
2028                       PFID(&hai->hai_fid),
2029                       hsm_copytool_action2name(hai->hai_action), rq_flags,
2030                       hai->hai_extent.offset, hai->hai_extent.length,
2031                       hsm->mh_flags,
2032                       (is_compat ? "compatible" : "uncompatible"));
2033
2034         RETURN(is_compat);
2035 }
2036
2037 /*
2038  * sysfs interface used to get/set HSM behaviour (cdt->cdt_policy)
2039  */
2040 static const struct {
2041         __u64            bit;
2042         char            *name;
2043         char            *nickname;
2044 } hsm_policy_names[] = {
2045         { CDT_NONBLOCKING_RESTORE,      "NonBlockingRestore",   "NBR"},
2046         { CDT_NORETRY_ACTION,           "NoRetryAction",        "NRA"},
2047         { 0 },
2048 };
2049
2050 /**
2051  * convert a policy name to a bit
2052  * \param name [IN] policy name
2053  * \retval 0 unknown
2054  * \retval   policy bit
2055  */
2056 static __u64 hsm_policy_str2bit(const char *name)
2057 {
2058         int      i;
2059
2060         for (i = 0; hsm_policy_names[i].bit != 0; i++)
2061                 if (strcmp(hsm_policy_names[i].nickname, name) == 0 ||
2062                     strcmp(hsm_policy_names[i].name, name) == 0)
2063                         return hsm_policy_names[i].bit;
2064         return 0;
2065 }
2066
2067 /**
2068  * convert a policy bit field to a string
2069  * \param mask [IN] policy bit field
2070  * \param hexa [IN] print mask before bit names
2071  * \param buffer [OUT] string
2072  * \param count [IN] size of buffer
2073  */
2074 static void hsm_policy_bit2str(struct seq_file *m, const __u64 mask,
2075                                 const bool hexa)
2076 {
2077         int      i, j;
2078         __u64    bit;
2079         ENTRY;
2080
2081         if (hexa)
2082                 seq_printf(m, "(%#llx) ", mask);
2083
2084         for (i = 0; i < CDT_POLICY_SHIFT_COUNT; i++) {
2085                 bit = (1ULL << i);
2086
2087                 for (j = 0; hsm_policy_names[j].bit != 0; j++) {
2088                         if (hsm_policy_names[j].bit == bit)
2089                                 break;
2090                 }
2091                 if (bit & mask)
2092                         seq_printf(m, "[%s] ", hsm_policy_names[j].name);
2093                 else
2094                         seq_printf(m, "%s ", hsm_policy_names[j].name);
2095         }
2096         /* remove last ' ' */
2097         m->count--;
2098         seq_putc(m, '\n');
2099 }
2100
2101 /* methods to read/write HSM policy flags */
2102 static int mdt_hsm_policy_seq_show(struct seq_file *m, void *data)
2103 {
2104         struct mdt_device       *mdt = m->private;
2105         struct coordinator      *cdt = &mdt->mdt_coordinator;
2106         ENTRY;
2107
2108         hsm_policy_bit2str(m, cdt->cdt_policy, false);
2109         RETURN(0);
2110 }
2111
2112 static ssize_t
2113 mdt_hsm_policy_seq_write(struct file *file, const char __user *buffer,
2114                          size_t count, loff_t *off)
2115 {
2116         struct seq_file         *m = file->private_data;
2117         struct mdt_device       *mdt = m->private;
2118         struct coordinator      *cdt = &mdt->mdt_coordinator;
2119         char                    *start, *token, sign;
2120         char                    *buf;
2121         __u64                    policy;
2122         __u64                    add_mask, remove_mask, set_mask;
2123         int                      rc;
2124         ENTRY;
2125
2126         if (count + 1 > PAGE_SIZE)
2127                 RETURN(-EINVAL);
2128
2129         OBD_ALLOC(buf, count + 1);
2130         if (buf == NULL)
2131                 RETURN(-ENOMEM);
2132
2133         if (copy_from_user(buf, buffer, count))
2134                 GOTO(out, rc = -EFAULT);
2135
2136         buf[count] = '\0';
2137
2138         start = buf;
2139         CDEBUG(D_HSM, "%s: receive new policy: '%s'\n", mdt_obd_name(mdt),
2140                start);
2141
2142         add_mask = remove_mask = set_mask = 0;
2143         do {
2144                 token = strsep(&start, "\n ");
2145                 sign = *token;
2146
2147                 if (sign == '\0')
2148                         continue;
2149
2150                 if (sign == '-' || sign == '+')
2151                         token++;
2152
2153                 policy = hsm_policy_str2bit(token);
2154                 if (policy == 0) {
2155                         CWARN("%s: '%s' is unknown, "
2156                               "supported policies are:\n", mdt_obd_name(mdt),
2157                               token);
2158                         hsm_policy_bit2str(m, 0, false);
2159                         GOTO(out, rc = -EINVAL);
2160                 }
2161                 switch (sign) {
2162                 case '-':
2163                         remove_mask |= policy;
2164                         break;
2165                 case '+':
2166                         add_mask |= policy;
2167                         break;
2168                 default:
2169                         set_mask |= policy;
2170                         break;
2171                 }
2172
2173         } while (start != NULL);
2174
2175         CDEBUG(D_HSM, "%s: new policy: rm=%#llx add=%#llx set=%#llx\n",
2176                mdt_obd_name(mdt), remove_mask, add_mask, set_mask);
2177
2178         /* if no sign in all string, it is a clear and set
2179          * if some sign found, all unsigned are converted
2180          * to add
2181          * P1 P2 = set to P1 and P2
2182          * P1 -P2 = add P1 clear P2 same as +P1 -P2
2183          */
2184         if (remove_mask == 0 && add_mask == 0) {
2185                 cdt->cdt_policy = set_mask;
2186         } else {
2187                 cdt->cdt_policy |= set_mask | add_mask;
2188                 cdt->cdt_policy &= ~remove_mask;
2189         }
2190
2191         GOTO(out, rc = count);
2192
2193 out:
2194         OBD_FREE(buf, count + 1);
2195         RETURN(rc);
2196 }
2197 LDEBUGFS_SEQ_FOPS(mdt_hsm_policy);
2198
2199 static ssize_t loop_period_show(struct kobject *kobj, struct attribute *attr,
2200                                 char *buf)
2201 {
2202         struct coordinator *cdt = container_of(kobj, struct coordinator,
2203                                                cdt_hsm_kobj);
2204
2205         return scnprintf(buf, PAGE_SIZE, "%u\n", cdt->cdt_loop_period);
2206 }
2207
2208 static ssize_t loop_period_store(struct kobject *kobj, struct attribute *attr,
2209                                  const char *buffer, size_t count)
2210 {
2211         struct coordinator *cdt = container_of(kobj, struct coordinator,
2212                                                cdt_hsm_kobj);
2213         unsigned int val;
2214         int rc;
2215
2216         rc = kstrtouint(buffer, 0, &val);
2217         if (rc)
2218                 return rc;
2219
2220         if (val != 0)
2221                 cdt->cdt_loop_period = val;
2222
2223         return val ? count : -EINVAL;
2224 }
2225 LUSTRE_RW_ATTR(loop_period);
2226
2227 static ssize_t grace_delay_show(struct kobject *kobj, struct attribute *attr,
2228                                 char *buf)
2229 {
2230         struct coordinator *cdt = container_of(kobj, struct coordinator,
2231                                                cdt_hsm_kobj);
2232
2233         return scnprintf(buf, PAGE_SIZE, "%u\n", cdt->cdt_grace_delay);
2234 }
2235
2236 static ssize_t grace_delay_store(struct kobject *kobj, struct attribute *attr,
2237                                  const char *buffer, size_t count)
2238 {
2239         struct coordinator *cdt = container_of(kobj, struct coordinator,
2240                                                cdt_hsm_kobj);
2241         unsigned int val;
2242         int rc;
2243
2244         rc = kstrtouint(buffer, 0, &val);
2245         if (rc)
2246                 return rc;
2247
2248         if (val != 0)
2249                 cdt->cdt_grace_delay = val;
2250
2251         return val ? count : -EINVAL;
2252 }
2253 LUSTRE_RW_ATTR(grace_delay);
2254
2255 static ssize_t active_request_timeout_show(struct kobject *kobj,
2256                                            struct attribute *attr,
2257                                            char *buf)
2258 {
2259         struct coordinator *cdt = container_of(kobj, struct coordinator,
2260                                                cdt_hsm_kobj);
2261
2262         return scnprintf(buf, PAGE_SIZE, "%d\n", cdt->cdt_active_req_timeout);
2263 }
2264
2265 static ssize_t active_request_timeout_store(struct kobject *kobj,
2266                                             struct attribute *attr,
2267                                             const char *buffer, size_t count)
2268 {
2269         struct coordinator *cdt = container_of(kobj, struct coordinator,
2270                                                cdt_hsm_kobj);
2271         unsigned int val;
2272         int rc;
2273
2274         rc = kstrtouint(buffer, 0, &val);
2275         if (rc)
2276                 return rc;
2277
2278         if (val != 0)
2279                 cdt->cdt_active_req_timeout = val;
2280
2281         return val ? count : -EINVAL;
2282 }
2283 LUSTRE_RW_ATTR(active_request_timeout);
2284
2285 static ssize_t max_requests_show(struct kobject *kobj, struct attribute *attr,
2286                                  char *buf)
2287 {
2288         struct coordinator *cdt = container_of(kobj, struct coordinator,
2289                                                cdt_hsm_kobj);
2290
2291         return scnprintf(buf, PAGE_SIZE, "%llu\n", cdt->cdt_max_requests);
2292 }
2293
2294 static ssize_t max_requests_store(struct kobject *kobj, struct attribute *attr,
2295                                   const char *buffer, size_t count)
2296 {
2297         struct coordinator *cdt = container_of(kobj, struct coordinator,
2298                                                cdt_hsm_kobj);
2299         unsigned long long val;
2300         int rc;
2301
2302         rc = kstrtoull(buffer, 0, &val);
2303         if (rc)
2304                 return rc;
2305
2306         if (val != 0)
2307                 cdt->cdt_max_requests = val;
2308
2309         return val ? count : -EINVAL;
2310 }
2311 LUSTRE_RW_ATTR(max_requests);
2312
2313 static ssize_t default_archive_id_show(struct kobject *kobj,
2314                                        struct attribute *attr, char *buf)
2315 {
2316         struct coordinator *cdt = container_of(kobj, struct coordinator,
2317                                                cdt_hsm_kobj);
2318
2319         return scnprintf(buf, PAGE_SIZE, "%u\n", cdt->cdt_default_archive_id);
2320 }
2321
2322 static ssize_t default_archive_id_store(struct kobject *kobj,
2323                                         struct attribute *attr,
2324                                         const char *buffer, size_t count)
2325 {
2326         struct coordinator *cdt = container_of(kobj, struct coordinator,
2327                                                cdt_hsm_kobj);
2328         unsigned int val;
2329         int rc;
2330
2331         rc = kstrtouint(buffer, 0, &val);
2332         if (rc)
2333                 return rc;
2334
2335         if (val != 0)
2336                 cdt->cdt_default_archive_id = val;
2337
2338         return val ? count : -EINVAL;
2339 }
2340 LUSTRE_RW_ATTR(default_archive_id);
2341
2342 /*
2343  * procfs write method for MDT/hsm_control
2344  * proc entry is in mdt directory so data is mdt obd_device pointer
2345  */
2346 #define CDT_ENABLE_CMD   "enabled"
2347 #define CDT_STOP_CMD     "shutdown"
2348 #define CDT_DISABLE_CMD  "disabled"
2349 #define CDT_PURGE_CMD    "purge"
2350 #define CDT_HELP_CMD     "help"
2351 #define CDT_MAX_CMD_LEN  10
2352
2353 ssize_t hsm_control_store(struct kobject *kobj, struct attribute *attr,
2354                           const char *buffer, size_t count)
2355 {
2356         struct obd_device *obd = container_of(kobj, struct obd_device,
2357                                               obd_kset.kobj);
2358         struct mdt_device *mdt = mdt_dev(obd->obd_lu_dev);
2359         struct coordinator *cdt = &(mdt->mdt_coordinator);
2360         int usage = 0;
2361         int rc = 0;
2362
2363         if (count == 0 || count >= CDT_MAX_CMD_LEN)
2364                 return -EINVAL;
2365
2366         if (strncmp(buffer, CDT_ENABLE_CMD, strlen(CDT_ENABLE_CMD)) == 0) {
2367                 if (cdt->cdt_state == CDT_DISABLE) {
2368                         rc = set_cdt_state(cdt, CDT_RUNNING);
2369                         mdt_hsm_cdt_event(cdt);
2370                         wake_up(&cdt->cdt_waitq);
2371                 } else if (cdt->cdt_state == CDT_RUNNING) {
2372                         rc = 0;
2373                 } else {
2374                         rc = mdt_hsm_cdt_start(mdt);
2375                 }
2376         } else if (strncmp(buffer, CDT_STOP_CMD, strlen(CDT_STOP_CMD)) == 0) {
2377                 if (cdt->cdt_state == CDT_STOPPING) {
2378                         CERROR("%s: Coordinator is already stopping\n",
2379                                mdt_obd_name(mdt));
2380                         rc = -EALREADY;
2381                 } else if (cdt->cdt_state == CDT_STOPPED) {
2382                         rc = 0;
2383                 } else {
2384                         rc = mdt_hsm_cdt_stop(mdt);
2385                 }
2386         } else if (strncmp(buffer, CDT_DISABLE_CMD,
2387                            strlen(CDT_DISABLE_CMD)) == 0) {
2388                 if ((cdt->cdt_state == CDT_STOPPING) ||
2389                     (cdt->cdt_state == CDT_STOPPED)) {
2390                         /* exit gracefully if coordinator is being stopped
2391                          * or stopped already.
2392                          */
2393                         rc = 0;
2394                 } else {
2395                         rc = set_cdt_state(cdt, CDT_DISABLE);
2396                 }
2397         } else if (strncmp(buffer, CDT_PURGE_CMD,
2398                            strlen(CDT_PURGE_CMD)) == 0) {
2399                 rc = hsm_cancel_all_actions(mdt);
2400         } else if (strncmp(buffer, CDT_HELP_CMD,
2401                            strlen(CDT_HELP_CMD)) == 0) {
2402                 usage = 1;
2403         } else {
2404                 usage = 1;
2405                 rc = -EINVAL;
2406         }
2407
2408         if (usage == 1)
2409                 CERROR("%s: Valid coordinator control commands are: "
2410                        "%s %s %s %s %s\n", mdt_obd_name(mdt),
2411                        CDT_ENABLE_CMD, CDT_STOP_CMD, CDT_DISABLE_CMD,
2412                        CDT_PURGE_CMD, CDT_HELP_CMD);
2413
2414         if (rc)
2415                 RETURN(rc);
2416
2417         RETURN(count);
2418 }
2419
2420 ssize_t hsm_control_show(struct kobject *kobj, struct attribute *attr,
2421                          char *buf)
2422 {
2423         struct obd_device *obd = container_of(kobj, struct obd_device,
2424                                               obd_kset.kobj);
2425         struct coordinator *cdt;
2426
2427         cdt = &(mdt_dev(obd->obd_lu_dev)->mdt_coordinator);
2428
2429         return scnprintf(buf, PAGE_SIZE, "%s\n",
2430                          cdt_mdt_state2str(cdt->cdt_state));
2431 }
2432
2433 static int
2434 mdt_hsm_request_mask_show(struct seq_file *m, __u64 mask)
2435 {
2436         bool first = true;
2437         int i;
2438         ENTRY;
2439
2440         for (i = 0; i < 8 * sizeof(mask); i++) {
2441                 if (mask & (1UL << i)) {
2442                         seq_printf(m, "%s%s", first ? "" : " ",
2443                                    hsm_copytool_action2name(i));
2444                         first = false;
2445                 }
2446         }
2447         seq_putc(m, '\n');
2448
2449         RETURN(0);
2450 }
2451
2452 static int
2453 mdt_hsm_user_request_mask_seq_show(struct seq_file *m, void *data)
2454 {
2455         struct mdt_device *mdt = m->private;
2456         struct coordinator *cdt = &mdt->mdt_coordinator;
2457
2458         return mdt_hsm_request_mask_show(m, cdt->cdt_user_request_mask);
2459 }
2460
2461 static int
2462 mdt_hsm_group_request_mask_seq_show(struct seq_file *m, void *data)
2463 {
2464         struct mdt_device *mdt = m->private;
2465         struct coordinator *cdt = &mdt->mdt_coordinator;
2466
2467         return mdt_hsm_request_mask_show(m, cdt->cdt_group_request_mask);
2468 }
2469
2470 static int
2471 mdt_hsm_other_request_mask_seq_show(struct seq_file *m, void *data)
2472 {
2473         struct mdt_device *mdt = m->private;
2474         struct coordinator *cdt = &mdt->mdt_coordinator;
2475
2476         return mdt_hsm_request_mask_show(m, cdt->cdt_other_request_mask);
2477 }
2478
2479 static inline enum hsm_copytool_action
2480 hsm_copytool_name2action(const char *name)
2481 {
2482         if (strcasecmp(name, "NOOP") == 0)
2483                 return HSMA_NONE;
2484         else if (strcasecmp(name, "ARCHIVE") == 0)
2485                 return HSMA_ARCHIVE;
2486         else if (strcasecmp(name, "RESTORE") == 0)
2487                 return HSMA_RESTORE;
2488         else if (strcasecmp(name, "REMOVE") == 0)
2489                 return HSMA_REMOVE;
2490         else if (strcasecmp(name, "CANCEL") == 0)
2491                 return HSMA_CANCEL;
2492         else
2493                 return -1;
2494 }
2495
2496 static ssize_t
2497 mdt_write_hsm_request_mask(struct file *file, const char __user *user_buf,
2498                             size_t user_count, __u64 *mask)
2499 {
2500         char *buf, *pos, *name;
2501         size_t buf_size;
2502         __u64 new_mask = 0;
2503         int rc;
2504         ENTRY;
2505
2506         if (!(user_count < 4096))
2507                 RETURN(-ENOMEM);
2508
2509         buf_size = user_count + 1;
2510
2511         OBD_ALLOC(buf, buf_size);
2512         if (buf == NULL)
2513                 RETURN(-ENOMEM);
2514
2515         if (copy_from_user(buf, user_buf, buf_size - 1))
2516                 GOTO(out, rc = -EFAULT);
2517
2518         buf[buf_size - 1] = '\0';
2519
2520         pos = buf;
2521         while ((name = strsep(&pos, " \t\v\n")) != NULL) {
2522                 int action;
2523
2524                 if (*name == '\0')
2525                         continue;
2526
2527                 action = hsm_copytool_name2action(name);
2528                 if (action < 0)
2529                         GOTO(out, rc = -EINVAL);
2530
2531                 new_mask |= (1UL << action);
2532         }
2533
2534         *mask = new_mask;
2535         rc = user_count;
2536 out:
2537         OBD_FREE(buf, buf_size);
2538
2539         RETURN(rc);
2540 }
2541
2542 static ssize_t
2543 mdt_hsm_user_request_mask_seq_write(struct file *file, const char __user *buf,
2544                                         size_t count, loff_t *off)
2545 {
2546         struct seq_file         *m = file->private_data;
2547         struct mdt_device       *mdt = m->private;
2548         struct coordinator *cdt = &mdt->mdt_coordinator;
2549
2550         return mdt_write_hsm_request_mask(file, buf, count,
2551                                            &cdt->cdt_user_request_mask);
2552 }
2553
2554 static ssize_t
2555 mdt_hsm_group_request_mask_seq_write(struct file *file, const char __user *buf,
2556                                         size_t count, loff_t *off)
2557 {
2558         struct seq_file         *m = file->private_data;
2559         struct mdt_device       *mdt = m->private;
2560         struct coordinator      *cdt = &mdt->mdt_coordinator;
2561
2562         return mdt_write_hsm_request_mask(file, buf, count,
2563                                            &cdt->cdt_group_request_mask);
2564 }
2565
2566 static ssize_t
2567 mdt_hsm_other_request_mask_seq_write(struct file *file, const char __user *buf,
2568                                         size_t count, loff_t *off)
2569 {
2570         struct seq_file         *m = file->private_data;
2571         struct mdt_device       *mdt = m->private;
2572         struct coordinator      *cdt = &mdt->mdt_coordinator;
2573
2574         return mdt_write_hsm_request_mask(file, buf, count,
2575                                            &cdt->cdt_other_request_mask);
2576 }
2577
2578 static ssize_t remove_archive_on_last_unlink_show(struct kobject *kobj,
2579                                                   struct attribute *attr,
2580                                                   char *buf)
2581 {
2582         struct coordinator *cdt = container_of(kobj, struct coordinator,
2583                                                cdt_hsm_kobj);
2584
2585         return scnprintf(buf, PAGE_SIZE, "%u\n",
2586                          cdt->cdt_remove_archive_on_last_unlink);
2587 }
2588
2589 static ssize_t remove_archive_on_last_unlink_store(struct kobject *kobj,
2590                                                    struct attribute *attr,
2591                                                    const char *buffer,
2592                                                    size_t count)
2593 {
2594         struct coordinator *cdt = container_of(kobj, struct coordinator,
2595                                                cdt_hsm_kobj);
2596         bool val;
2597         int rc;
2598
2599         rc = kstrtobool(buffer, &val);
2600         if (rc < 0)
2601                 return rc;
2602
2603         cdt->cdt_remove_archive_on_last_unlink = val;
2604         return count;
2605 }
2606 LUSTRE_RW_ATTR(remove_archive_on_last_unlink);
2607
2608 LDEBUGFS_SEQ_FOPS(mdt_hsm_user_request_mask);
2609 LDEBUGFS_SEQ_FOPS(mdt_hsm_group_request_mask);
2610 LDEBUGFS_SEQ_FOPS(mdt_hsm_other_request_mask);
2611
2612 /* Read-only sysfs files for request counters */
2613 static ssize_t archive_count_show(struct kobject *kobj, struct attribute *attr,
2614                                   char *buf)
2615 {
2616         struct coordinator *cdt = container_of(kobj, struct coordinator,
2617                                                cdt_hsm_kobj);
2618
2619         return scnprintf(buf, PAGE_SIZE, "%d\n",
2620                          atomic_read(&cdt->cdt_archive_count));
2621 }
2622 LUSTRE_RO_ATTR(archive_count);
2623
2624 static ssize_t restore_count_show(struct kobject *kobj, struct attribute *attr,
2625                                   char *buf)
2626 {
2627         struct coordinator *cdt = container_of(kobj, struct coordinator,
2628                                                cdt_hsm_kobj);
2629
2630         return scnprintf(buf, PAGE_SIZE, "%d\n",
2631                          atomic_read(&cdt->cdt_restore_count));
2632 }
2633 LUSTRE_RO_ATTR(restore_count);
2634
2635 static ssize_t remove_count_show(struct kobject *kobj, struct attribute *attr,
2636                                  char *buf)
2637 {
2638         struct coordinator *cdt = container_of(kobj, struct coordinator,
2639                                                cdt_hsm_kobj);
2640
2641         return scnprintf(buf, PAGE_SIZE, "%d\n",
2642                          atomic_read(&cdt->cdt_remove_count));
2643 }
2644 LUSTRE_RO_ATTR(remove_count);
2645
2646 static struct ldebugfs_vars ldebugfs_mdt_hsm_vars[] = {
2647         { .name =       "agents",
2648           .fops =       &mdt_hsm_agent_fops                     },
2649         { .name =       "actions",
2650           .fops =       &mdt_hsm_actions_fops,
2651           .proc_mode =  0444                                    },
2652         { .name =       "policy",
2653           .fops =       &mdt_hsm_policy_fops                    },
2654         { .name =       "active_requests",
2655           .fops =       &mdt_hsm_active_requests_fops           },
2656         { .name =       "user_request_mask",
2657           .fops =       &mdt_hsm_user_request_mask_fops,        },
2658         { .name =       "group_request_mask",
2659           .fops =       &mdt_hsm_group_request_mask_fops,       },
2660         { .name =       "other_request_mask",
2661           .fops =       &mdt_hsm_other_request_mask_fops,       },
2662         { 0 }
2663 };
2664
2665 static struct attribute *hsm_attrs[] = {
2666         &lustre_attr_loop_period.attr,
2667         &lustre_attr_grace_delay.attr,
2668         &lustre_attr_active_request_timeout.attr,
2669         &lustre_attr_max_requests.attr,
2670         &lustre_attr_default_archive_id.attr,
2671         &lustre_attr_remove_archive_on_last_unlink.attr,
2672         &lustre_attr_archive_count.attr,
2673         &lustre_attr_restore_count.attr,
2674         &lustre_attr_remove_count.attr,
2675         NULL,
2676 };
2677
2678 KOBJ_ATTRIBUTE_GROUPS(hsm); /* creates hsm_groups from hsm_attrs */
2679
2680 static void hsm_kobj_release(struct kobject *kobj)
2681 {
2682         struct coordinator *cdt = container_of(kobj, struct coordinator,
2683                                                cdt_hsm_kobj);
2684
2685         debugfs_remove_recursive(cdt->cdt_debugfs_dir);
2686         cdt->cdt_debugfs_dir = NULL;
2687
2688         complete(&cdt->cdt_kobj_unregister);
2689 }
2690
2691 static struct kobj_type hsm_ktype = {
2692         .default_groups = KOBJ_ATTR_GROUPS(hsm),
2693         .sysfs_ops      = &lustre_sysfs_ops,
2694         .release        = hsm_kobj_release,
2695 };
2696
2697 /**
2698  * create sysfs entries for coordinator
2699  * \param mdt [IN]
2700  * \retval 0 success
2701  * \retval -ve failure
2702  */
2703 int hsm_cdt_tunables_init(struct mdt_device *mdt)
2704 {
2705         struct coordinator *cdt = &mdt->mdt_coordinator;
2706         struct obd_device *obd = mdt2obd_dev(mdt);
2707         int rc;
2708
2709         init_completion(&cdt->cdt_kobj_unregister);
2710         rc = kobject_init_and_add(&cdt->cdt_hsm_kobj, &hsm_ktype,
2711                                   &obd->obd_kset.kobj, "%s", "hsm");
2712         if (rc) {
2713                 kobject_put(&cdt->cdt_hsm_kobj);
2714                 return rc;
2715         }
2716
2717         /* init debugfs entries, failure is not critical */
2718         cdt->cdt_debugfs_dir = debugfs_create_dir("hsm",
2719                                                   obd->obd_debugfs_entry);
2720         ldebugfs_add_vars(cdt->cdt_debugfs_dir, ldebugfs_mdt_hsm_vars, mdt);
2721
2722         return 0;
2723 }
2724
2725 /**
2726  * remove sysfs entries for coordinator
2727  *
2728  * @mdt
2729  */
2730 void hsm_cdt_tunables_fini(struct mdt_device *mdt)
2731 {
2732         struct coordinator *cdt = &mdt->mdt_coordinator;
2733
2734         kobject_put(&cdt->cdt_hsm_kobj);
2735         wait_for_completion(&cdt->cdt_kobj_unregister);
2736 }