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