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